the code is given below: it gives output true2.
#include<stdio.h>
int main()
{
int a=10;
if(a==a--)
printf("true 1\t");
a=10;
if(a==--a)
printf("true2 \t");
return 0;
}
the code is given below: it gives output true2.
#include<stdio.h>
int main()
{
int a=10;
if(a==a--)
printf("true 1\t");
a=10;
if(a==--a)
printf("true2 \t");
return 0;
}
The comparison done in both of the if
statements result in undefined behaviour. So, anything could happen. Because a
is read and modified without an intervening sequence point. The comparison operator ==
doesn't introduce a sequence point. You probably need to learn about undefined behaviour and sequence points, etc to understand the problem better.
Modern compilers may also help you. For example, Clang issues:
warning: unsequenced modification and access to 'a' [-Wunsequenced]
if(a==a--)
~ ^
warning: unsequenced modification and access to 'a' [-Wunsequenced]
if(a==--a)
~ ^
for the two if
statements (GCC also produces similar warnings with gcc -Wall -Wextra
).
In general, it is not a good practice to do a-- (or --a) inside a condition, because it is not clear to read. In order to understand the difference between a-- and --a please see the answer at: Incrementing in C++ - When to use x++ or ++x?