简体   繁体   中英

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 int i; i >> 3 . But why this is implementation-defined?

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 int i; i >> 3 is undefined behavior since the variable isn't initialized.

The specific example int i=0; i >> 3 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.

It's implementation defined because the C standards committee declined to define what should happen. The reason why they did that is because different CPUs do different things in such circumstances, and the ethos of C (in the interests of fast execution) is to not to put too much abstraction between the C source code and the op codes running on the CPU.

They could have chosen to define a standard behaviour, but then on some CPUs that'd require compilers to generate a load of code to make up for the fact that the CPU's own op codes don't provide that standardised behaviour. Whilst perfectly possible, it inevitably wouldn't be very efficient.

Others will no doubt be able to point to more authoritative versions of that explanation!

Any code that relies on implementation defined behaviour is only guaranteed to work under a specific platform and/or compiler. Portable programs should try to avoid such behaviour.

According to: https://clc-wiki.net/wiki/C_language:Terms:Implementation-defined_behaviour

That also gives another example:

int *o = malloc(0 * sizeof *o);

may result in o either being NULL or a unique pointer (as specified in 7.20.3 of the C99 Standard).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM