cmisraimplementation-defined-behavior

Implementation-defined behavior in C


Please, can you report some example for implementation-defined behavior in C?

For example, I know from standard that "An implementation-defined behavior is the propagation of the high-order bit when a signed integer is shifted right."

Can you explain to me the significant of the example and report an example?

I understand that int i; i >> 3. But why this is implementation-defined?


Solution

  • The definition of implementation-defined behavior in C is when something is left for the compiler to decide, and the compiler documents which choice it made.

    There are hundreds of such cases in the language. The standard contains a summary of most of them in Annex J.3, which is ~15 pages long.

    The specific example int i; i >> 3 is undefined behavior since the variable isn't initialized.

    The specific example int i=0; i >> 3 is implementation-defined because the standard says so. C17 6.5.7/5:

    The result of E1 >> E2 is E1 right-shifted E2 bit positions. /--/ If E1 has a signed type and a negative value, the resulting value is implementation-defined.

    In this particular case, it depends on whether the compiler picks an arithmetic shift or a logical shift instruction from the CPU instruction set. Meaning that the standard doesn't disfavour architectures that lack an arithmetic shift. Though in practice, the vast majority of CPUs are capable of doing arithmetic shift, even RISC ones.