int main()
{
int c=5;
printf("%d\n%d\n%d", c, c<<=2, c>>=2);
return 0;
}
I am not getting how the assignment is taking place in the printf function. The output is coming out to be 4,4,4 but according to me it should be 4,4,1.
int main()
{
int c=5;
printf("%d\n%d\n%d", c, c<<=2, c>>=2);
return 0;
}
I am not getting how the assignment is taking place in the printf function. The output is coming out to be 4,4,4 but according to me it should be 4,4,1.
There are no sequence points between your modifications of c
and so the behaviour is undefined.
You need to impose sequence explicitly. For example:
int main(void)
{
int c = 5;
int d = c >> 2;
int e = d << 2;
printf("%d\n%d\n%d", c, e, d);
return 0;
}
You should, as a matter of course, ask your compiler to report warnings. If you do so, and assuming that your compiler is competent, then it will warn you of the issue. For instance, my GCC when asked to compile your program using the -Wall
option reports:
main.c: In function 'main': main.c:6:37: warning: operation on 'c' may be undefined [-Wsequence-point] printf("%d\n%d\n%d", c, c<<=2, c>>=2); ^ main.c:6:37: warning: operation on 'c' may be undefined [-Wsequence-point]
You should use -Wall
flag when compiling.
I got:
../main.c:6:37: warning: operation on ‘c’ may be undefined [-Wsequence-point]
../main.c:6:37: warning: operation on ‘c’ may be undefined [-Wsequence-point]
This code for example is broken:
c<<=2
since There are no sequence points between your modifications of c
.
It should be something like this:
int a = c << 2;
As a result, your code leads to undefined behaviour.