Hey can anyone explain the following code to me

#define SQUARED(x) {x * x}

int main()
{

int i = SQUARED(3 + 2);

return 0;
}

Why does 'i' in the above code = 11 and not 25????

Recommended Answers

All 7 Replies

It's evaluated as ((3 + (2 * 3)) + 2), not ((3 + 2) * (3 + 2)). If you don't wrap your macro arguments in parentheses, you may not get the evaluation order you wanted.

Wow thanks alot much appreciated, hey do you have any further detail into this, like do you know why it is evaluated in that way???? If not its kl you've helped out alot so far (Y)

It's evaluated that way because of the mathematical order of operations.

Look again.

//with this macro
#define SQUARED(x) (x*x)

//this line:
int i = SQUARED(3 + 2)

//literally becomes this
int i = [B]( 3 + 2 * 3 + 2)[/B];

//order of operations says multiplication occurs before addition
int i = ( 3 + [B]6[/B] + 2);

//remaining addition occurs from left to right
int i = ( [B]9[/B] + 2);
int i = ( [B]11[/B] );

You MUST watch your parentheses when defining macros.

OMG now it makes so much sense.

Yeah I kinda figured from before that If I place the expression within parantheses then it comes out the way I expected it I just didnt understand why it came out different without the parantheses.

Thanks so much

(Y):D

Actually, it's rather remarkable that the code you posted should work at all. You may have thought that you wrote

#define SQUARED(x) (x * x)

but what you actually wrote is

#define SQUARED(x) {x * x}

so that your statement

int i = SQUARED(3 + 2);

should expand to

int i = {3 + 2 * 3 + 2};

As it happens, however, C++ allows initializers to be enclosed in curly braces. This usage is important for initializing arrays and structures. So the expansion of your example is equivalent to

int i = 3 + 2 * 3 + 2;

which, as mentioned earlier, evaluates to 11.

Yeah what I should have is

#define SQUARED(x) ((x) * (x))

Yeah what I should have is

#define SQUARED(x) ((x) * (x))

Yes -- but what I am pointing out is that the code you actually posted uses curly braces { } where I think you intended to use parentheses ( ).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.