-2

Kindly explain the output for the following code:

#include<stdio.h>
#include<stdlib.h>

#define SQUARE(x) (x*x*x)

int main() {
  int x = 3;
  int y = SQUARE(++x)/x++; // Undefined behavior even though it doesn't look 
                       // like it here
  printf("%d %d",x,y);
  return 0;
}

Output: 7 25

Please explain how the value of y comes to be 25?

  • your square function has to be (x*x), you'v defined a cube function – Memolition Aug 04 '13 at 14:46
  • 4
    When you have undefined behavior, any output is equally valid, and there's no real "explaining" any of it anyway. Therefore, even when/if you "fix" your `SQUARE` macro so it squares instead of cubing, your results will still be basically meaningless. – Jerry Coffin Aug 04 '13 at 14:47
  • 1
    You said **Undefined behavior** in the comment yourself, so what's so explain? – Yu Hao Aug 04 '13 at 14:47
  • your macro expands to `int y = (++x*++x*++x)/x++;` and this is pretty all you can says about this piece of code ... – user2485710 Aug 04 '13 at 14:54
  • And who is **The** up-voter? – haccks Aug 04 '13 at 15:02
  • Let's put it another way. What did you expect, and why? How did you assume the program flow would run? – Mr Lister Aug 04 '13 at 15:02

1 Answers1

0

The macro is misnamed, but that's just a red herring. The two statements expand to:

int x = 3;
int y = (++x * ++x * ++x) / x++;

This is undefined behavior, since x is being modified more than once between sequence points. The compiler is allowed to do almost anything; it can interleave the uses of x and the pre- and post-increments of x almost anyway it wants. It can do things left-to-right, in which case, you get:

int y = (4 * 5 * 6) / 6;

Under this scheme, x is now 7 and y is now 20.

It could have done things right-to-left:

int y = (7 * 6 * 5) / 3;

Now, y is 70.

It could have cached the value of x at almost any point and used it. Try running your program under various compilers, with various optimization levels. Does gcc -O4 differ from cc? In fact, quoting the Internet Jargon file:

nasal demons: n.

Recognized shorthand on the Usenet group comp.std.c for any unexpected behavior of a C compiler on encountering an undefined construct. During a discussion on that group in early 1992, a regular remarked “When the compiler encounters [a given undefined construct] it is legal for it to make demons fly out of your nose” (the implication is that the compiler may choose any arbitrarily bizarre way to interpret the code without violating the ANSI C standard). Someone else followed up with a reference to “nasal demons”, which quickly became established. The original post is web-accessible at http://groups.google.com/groups?hl=en&selm=10195%40ksr.com.

So, I'd be a lot more careful here. Do you want demons flying out of your nose?

Community
  • 1
  • 1
Eric Jablow
  • 7,874
  • 2
  • 22
  • 29