Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain the output of this C Program? [duplicate]

Tags:

c

#include<stdio.h>
#define CUBE(x) (x*x*x)

int main()
{
int a, b=3;
a = CUBE(++b);
printf("%d, %d\n", a, b);
return 0;
}

This code returns the value of a=150 and b=6. Please explain this.

I think when it executes the value of a will be calculated as a=4*5*6=120 but it isn't true according to the compiler , so please explain the logic....

like image 279
Mragank Yadav Avatar asked Dec 04 '22 12:12

Mragank Yadav


1 Answers

There's no logic, it's undefined behavior because

++b * ++b * ++b;

modifies and reads b 3 times with no interleaving sequence points.

Bonus: You'll see another weird behavior if you try CUBE(1+2).

like image 164
Luchian Grigore Avatar answered Dec 26 '22 05:12

Luchian Grigore