Undefined behavior in C language (Undefined Behavior) refers to the behavior that the C language standard does not prescribe. At the same time, the standard never requires the compiler to judge undefined behavior, so these behaviors are handled by the compiler itself, may produce different results in different compilers, or if the program calls undefined behavior, it may compile successfully, or even at first run without errors, only on another system, It even failed to run on another date. When an instance of undefined behavior occurs, as the language standard says, "Anything can happen", perhaps nothing happens.
Therefore, it is a wise decision to avoid undefined behavior. This article will describe several undefined behaviors, and welcome readers to correct and supplement them.
1. Order of calculation for multiple operands in the same operator (except for &&, | |,?, and, operators)
For example: x = f () +g (); Error
F () and g () who calculate first by the compiler determines that if the function f or G changes the value of the variable used by another function, then the result of X may depend on the order in which the two functions are evaluated.
reference: "C programming language (2nd edition)" P43
2. Order of evaluation of function parameters
For example: printf ("%d,%d\n", ++n,power (2,n)); Error
The different compilers may produce different results, depending on the N self-increment operation and Power calls who are in front of them.
It is important to note that you do not mix with the comma expression, you can refer to this article: the comma operator and the comma expression in the C language
reference: "C programming language (2nd edition)" P43
3. Directly modify the value of the const constant via the pointer
Modifying the value of a const variable directly by assigning a value will cause the compiler to give an error, but it will not, for example, be modified by a pointer:
123456789 |
int main() { const int a = 1; int *b = (int*)&a; *b = + ; printf("%d,%d", a, *b); return 0; } |
A output value is also determined by the compiler.
C language undefined behaviour undefined behavior