Give the output of the following program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#define func(x) x*x-x
using namespace std;
class abcd {
public:
static int a;
int b;
abcd(int x) {
b=x;
a=b+1;
}
};
int abcd::a=0;
int f, x=10, y=10, i=2;
char *s = "ABCD";
int *z = &x;
int main(void) {
cout << "func(i+3) is " << func(i+3) << endl;
f = (x==y);
cout << "f is " << f << endl;
while (++i<5) f *= i;
cout << "f is " << f << endl;
x = (x++ > y) ? (x+y) : (x-y);
cout << "x is " << x << endl;
x = y++ + x++;
y = ++y + ++x;
cout << "x is " << x++ << endl;
cout << "y is " << ++y << endl;
}


For the code above I get the output of func(i+3) is 20 using the #define function x*x-x. But the actual output is 12.
Also f is not assigned to anything but output is 1.
Can somebody please explain me how this code works?
define macros work by direct substitution. It's not like a function which evaluates an argument before it starts to process:
1
2
3
4
5
func(x)
x * x - x
func( i + 3 ) 
func( 2 + 3 )
2 + 3 * 2 + 3 - 2 + 3
2 + 5 + 3 - 2 + 3
11


Let's look at an alternative:
template <typename T> inline T func(x) { return x * x - x; }

This will give us:
1
2
3
4
5
func(i + 3)
func(2 + 3) 
func(5) // Functions will evaluate the inputs!
5*5-5
20



It's better to avoid macros when possible for this exact reason. Here's another example:
#define square(a) ( a * a )

Now le's stick i++ in here:
1
2
3
int i = 2;
square( i++); // You would expect i to be incremented once right?
(i++ * i++); // No! It's incremented twice! 
indentation
<nolyc> indentation is optional whitespace. see also: !vowel
vowel
<nolyc> vwls r bt s sfl s whtspc, spclly n vrbl nms. s ls: !ndnttn
ndnttn
<nolyc> indentation is optional whitespace. see also: !vowel


func(i+3) expands to `i+3*i+3-i+3'

> Also f is not assigned to anything but output is 1.
¿what did you expected then?
However you do have `f = (x==y);'

By the way, lines 25 and 26 have undefined behaviour


Edit:
1
2
#define square(a) ( (a)*(a) )
square( i++); //UB 
Last edited on
Thank you very much indeed. I understood it now. Your explanation was very helpful.
Also can you please explain me


1
2
f = (x==y);
cout << "f is " << f << endl;


I can see from the code f has been initialized but not assigned to anything.
I want to know how the output becomes 1.
Eliza0210 wrote:
but not assigned to anything.

What gave you that idea? Didn't you see the "=" sign? It is being assigned the value of the boolean expression (x==y).
I haven't done programming for a while. I think my mind completely forgotten about boolean expression. Thanks for helping me Stewbond ,
ne555 & booradley60.
Topic archived. No new replies allowed.