sir would you please tell me that why the following condition in 'C' is false
?
main()
{
int i=1;
if(i<=i++)
printf("false");
else
printf("true");
}
sir would you please tell me that why the following condition in 'C' is false
?
main()
{
int i=1;
if(i<=i++)
printf("false");
else
printf("true");
}
It's not false, you just print false
when it's true.
The comparison operator <=
doesn't specify which side will be evaluated first, the i
or the i++
, and there is no sequence point at the end of the left-hand operand to a comparison function (see http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html#Sequence-Points).
If the left side is evaluated first, you get:
if (1 <= 1)
If the right side is evaluated first, you get:
if (2 <= 1)
This highlights the problem, but it's even worse than that.
You have written code with undefined behaviour, which means exactly that, "undefined". The compiler can do anything in this case and still be compliant with the standard.
For example, these compilers (with -O3
) follow the else branch:
While these compilers (with -O3
) follow the true
branch:
g++-4.7 (Ubuntu/Linaro 4.7.3-2ubuntu1~12.04) 4.7.3
And other compilers could do something completely different.
This is a combination unspecified behavior and just plain and simple undefined behavior. So you can not predict the outcome of this code and the results can not be relied on. It is unspecified because in this line:
if(i<=i++)
we do not know whether the i
or the i++
will be evaluated first. The draft C99 standard section 6.5
paragraph 3 says:
The grouping of operators and operands is indicated by the syntax.74) Except as specified later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified.
The above mentioned line also is undefined behavior because between sequence points we are only allowed to modify a variable once and if we modify it we are only allowed to read the previous value to determine the new value to set. In this case we are reading the prior value to determine both i
and i++
. From the draft standard section 6.5
paragraph 2:
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 read only to determine the value to be stored.
To understand what your code is doing, I am going to re-write, only will be VERY explicit:
main()
{
int i=1;
if(i<=i) {
i++;
printf("false");
} else {
i++:
printf("true");
}
}
The i++
means to increment i after the comparison. In both branches of the if i is being incremented, so it is equivalent.