hi guys, can't understand why the answer of the following program is 7? Please explain..

#include <stdio.h>
#define SQ(x) x*x
int main()
{
	int a,b;
	a=5;
	b=-SQ(a+2);
	printf("%d",b);
	return 0;
}

thank you..

also why the answer of the following code is 766? why not 557?

int=5;
printf("%d %d %d",i,i++,++i);

thanks guys..

  1. SQ(a+2) == a+2*a+2 == a+(2*a)+2 you can fix this by protecting the macro and its args: #define SQ(x) ((x)*(x)) . The outer parentheses are not strictly needed here, I think, but are a good habit. For instance think about this:
    #define DBL(x) (x)+(x)
    printf("%d\n",3*DBL(2)) /*8 or 12?*/
  2. Parameters are not evaluated in a defined order, so the compiler is free to evaluate in any of 6 possible ways. Fix it by passing independent variables to the function, by evaluating the parameters yourself into temporary locals, and passing the (now independent) temporaries to the function, or by being very careful. This last option will lead to bugs, when you get sleepy or in a hurry, so make it a habit not to do that.

thanks all

  1. SQ(a+2) == a+2*a+2 == a+(2*a)+2 you can fix this by protecting the macro and its args: #define SQ(x) ((x)*(x)) .

yes that i understood..
But my question is for SQ(a+2) >> a+(2*a)+2 ...that means when a=5 the answer is 17.
But in the code i've posted it's -SQ(a+2) ...and the answer's coming is 7..
i want to know the logic behind that...
thank you

But my question is for SQ(a+2) >> a+(2*a)+2 ...that means when a=5 the answer is 17.

You could easily follow the same process griswolf already did he left out the - but put it in and you get

-SQ(a+2) == -a+2*a+2 == -a+(2*a)+2 == a+2

Therefore for a=5, -SQ(a+2) == 5

By the way the answer to your second post is its undefined behaviour.

thanks...rep+ to all.... :)

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.