Why does the following piece of C code print 12 12 12
int main(int argc, char const *argv[]) {
int a = 2, *f1, *f2;
f1 = f2 = &a;
*f2 += *f2 += a += 2.5;
printf("%i %i %i\n", a, *f1, *f2);
return 0;
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This line has Undefined Behavior because you change the value of
*f2(i.e.a) more than once within the same expression without an intervening sequence point. UB means that your program may print “Hello World”, it may crash, it may print12 12 12or12 12 1029or it may start eating your brains. Don’t rely on undefined behavior.To quote the C++ standard ( I know the question is tagged C, but I don’t have a C standard by me and I know the same rule holds in C)