Skip to content

Ensure signed integer type for stse_ReturnCode_t enum#85

Open
parmi93 wants to merge 1 commit intoSTMicroelectronics:mainfrom
parmi93:core/stse-return-codes-signed
Open

Ensure signed integer type for stse_ReturnCode_t enum#85
parmi93 wants to merge 1 commit intoSTMicroelectronics:mainfrom
parmi93:core/stse-return-codes-signed

Conversation

@parmi93
Copy link
Copy Markdown
Contributor

@parmi93 parmi93 commented May 1, 2026

This PR adds a sentinel value __STSE_SIGNED = -1 to the stse_ReturnCode_t enum to guarantee that the enum is always treated as a signed integer type across all compilers and platforms.

Why This Change?

In C, enumerations are implicitly convertible to integers, but the C standard does not mandate whether an enum type should be signed or unsigned. The actual underlying type depends on:

  1. Compiler implementation: Different compilers (GCC, Clang, MSVC, etc.) may make different choices
  2. Enum values: The compiler chooses a type that can represent all enumeration constants
  3. Platform: 32-bit vs 64-bit systems may yield different results

The Problem

Without this fix, users cannot write portable code to print stse_ReturnCode_t values. Depending on the platform and compiler, %u may be required on some systems while %d is needed on others, resulting in non-portable and potentially buggy code.

Without this fix, code like:

stse_ReturnCode_t rc = STSE_OK;
printf("Return code: %d\n", rc);

Could behave inconsistently:

  • On some compilers/platforms, the enum is unsigned, so %d gives incorrect output (user should use %u)
  • On others it's signed, so %d gives correct output

The Solution

By adding __STSE_SIGNED = -1 as the last enum value, we force the compiler to choose a signed integer type (since the enum now contains a negative value that must be representable).

This guarantees:

  • Consistent behavior across all compilers
  • Safe use of %d format specifier for printing enum values
  • No undefined behavior when comparing with negative values
  • Predictable enum promotion rules

Technical Details

Per C99/C11 standards, the underlying type of an enum is implementation-defined but must be capable of representing all enumerator values. By including a negative value, we ensure the enum's underlying type is signed integer, making printf() with %d portable and safe.

Add `__STSE_SIGNED = -1` as the last enum value to guarantee that
`stse_ReturnCode_t` is treated as a signed integer type across all
compilers. This allows printing enum values using the `%d` format
specifier reliably on all platforms.
@parmi93 parmi93 changed the title Ensure signed integer type for stse_ReturnCode_t enum Ensure signed integer type for stse_ReturnCode_t enum May 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant