I know that the following is undefined because I am trying to read and write the value of variable in the same expression, which is
int a=5;
a=a++;
but if it is so then why the following code snippet is not undefined
int a=5;
a=a+1;
as here also I am trying to modify value of a
and write to it at the same time.
Also explain why the standard is not curing this or removing this undefined behavior, in spite of the fact that they know that it is undefined?
In C the use of any automatic variable before it has been initialized yields undefined behavior, as does integer division by zero, signed integer overflow, indexing an array outside of its defined bounds (see buffer overflow), or null pointer dereferencing.
In computing (particularly, in programming), undefined value is a condition where an expression does not have a correct value, although it is syntactically correct. An undefined value must not be confused with empty string, Boolean "false" or other "empty" (but defined) values.
A program is said to have an unspecified behavior when the standard provides two or more possibilities but does not impose requirements on which should be chosen by the compiler writer. For Example, the order in which function fun1 and fun2 are called in the following expression is not specified! x = fun1() + fun2();
The reason why it is undefined is not that you read and write, it is that you write twice.
a++
means read a and increment it after reading, but we don't know if the ++ will happen before the assignment with =
(in which case the =
will overwrite with the old value of a) or after, in which case a will be incremented.
Just use a++;
:)
a = a + 1
does not have the problem as a is only written once.
why the following code snippet is not undefined
int a=5; a=a+1;
The Standard states that
Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored.
In case of a = a + 1
; a
is modified only once and the prior value of a
accessed only to determine the value to be stored in a
.
While in case of a=a++;
, a
is modified more than once-- by ++
operator in sub-expression a++
and by =
operator in assigning the result to left a
. Now it is not defined that which modification, either by ++
or by =
, will takes place first.
Almost all modern compiler with flag -Wall
would raise a warning, on compiling the first snippet, like:
[Warning] operation on 'a' may be undefined [-Wsequence-point]
Further reading: How can I understand complex expressions like the ones in this section, and avoid writing undefined ones?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With