Search code examples
cportabilityundefined-behaviorstm32iar

C Standard Undefined Behavior With Respect To Nonportable Projects


The C99 standard gives the following definition for undefined behavior:

Behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements.

If you're working on a project that will never be required to be portable, that is, the compiler and microcontroller won't change, can you safely use nonportable constructs that the International Standard says will result in undefined behavior if they are defined by the compiler or microcontroller you're using?


Solution

  • An implementation is free to define and document some C undefined behaviors.

    Rationale document for C99 for example says:

    Undefined behavior gives the implementor license not to catch certain program errors that are difficult to diagnose. It also identifies areas of possible conforming language extension: the implementor may augment the language by providing a definition of the officially undefined behavior.

    For example, gcc defines some undefined behavior regarding the bitwise shift operator:

    GCC does not use the latitude given in C99 only to treat certain aspects of signed '<<' as undefined [...]

    http://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html