This is not necessarily undefined behavior, because it is very dependent on the language version - however, in C ++ 14, everything is much clearer. In any case, there is no guarantee that you will receive a value of 1.
int i; in this context, declares i with automatic storage time and default initialization. For int initialization by default leaves a variable with an undefined value.- In C, an undefined value is defined in the standard:
i will have some value or representation of a trap. - The increment operation adds a value to the value of
i , which was undefined. If it was a trap view, it could raise a signal. (On your regular PC hardware and C or C ++ compiler, there will be no traps for int .) - While the C ++ 14 project, C ++ left open, which was implied by undefined; it was used but not defined. As soon as one can assume that this meant the same as in the C standard, but frankly, there are no guarantees.
- With C ++ 14 this was nailed, and with the exception of a limited number of operations with narrow characters, doing something with undefined values ββleads to undefined behavior.
In short: if it is C, this is not undefined behavior, but no promises that it will be 1; if it was pre-C ++ 14 C ++, it was not correctly specified in the standard, but at least there is no promises that it will be equal to 1; and C ++ 14 states that this behavior is undefined.
Here's an interesting and informative discussion of what indefinite means in C ++ in stackoverflow.
source share