Explain this C program

Please refer to the comments, Explain the third printf statement. Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h> 
#define x 12
#define y 7
#define z 5
#define w y+z

  int main() {
  	printf("%d\n",x*x); // displays 144 //ok
  	printf("%d\n",w);   // displays 12 // ok
    printf("%d\n", w*w) ;   // displays 47. Shouldn't this be 144?
return(0);
}
... this is a c++ forum, even though it runs in c++, it is essentially C.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;
#define x 12
#define y 7
#define z 5
#define w y+z

  int main() {
  cout<<x*x<<"\n"; // displays 144 //ok
  cout<<w<<"\n";    // displays 12 // ok
  cout<<w*w<<"\n";  ;   // displays 47. Shouldn't this be 144?
return(0);
}


Here, I converted the code to C++, Can you please explain this behaviour now?
But, if this isn't homework, this is how you would fix this.
1
2
3
#include <stdlib.h>
//...
#define w abs( y + z ) 
W is 12 or (7+5) so W*W would be 12*12=144, but this is using order of operations so the equation is actually: 7+5*7+5=47
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h> 
#define x 12
#define y 7
#define z 5
#define w y+z

int main() {
printf("%d\n",x*x); // displays 144 //ok
printf("%d\n",w);   // displays 12 // ok
printf("%d\n", w*w) ;   //same as doing 7+5*7+5=47.
return 0;
}
Last edited on
@poteto: This isn't homework, I don't get homework anymore. :P
@jasonwynn10: Thanks, that explains it.
no problem! I need a good question once in a while! :)
FWIW, this is one of the many, many reasons why you should avoid using #defines unless they are your only option.

This would be better:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <cstdio>
/*#define x 12   <- get rid of all this
#define y 7
#define z 5
#define w y+z
*/
const int x = 12; // <- replace with this
const int y = 7;
const int z = 5;
const int w = y+z;

int main() {
  printf("%d\n",x*x);     // displays 144 //ok
  printf("%d\n",w);       // displays 12 // ok
  printf("%d\n", w*w) ;   // displays 144 as you'd expect
  return 0;
}
Sincerely, Thank you all, this post has been very helpful!
Topic archived. No new replies allowed.