You have to be REALLLY REEEEEEEEEEEEEALLY careful with macros. To see why, we can get the c preprocessor to show us how it's expanded the macro:
Code:
$ cat > a.c << 'EOF'
> #define SQR(x) (x*x)
> main(){
>
> int a,b=3;
> a=SQR(b+2);
> printf("\n%d",a);
> }
> EOF
$ gcc a.c -E
# 1 "a.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "a.c"
main(){
int a,b=3;
a=(b+2*b+2);
printf("\n%d",a);
}
As you can see, SQR(b+2) gets expanded (correctly - i.e. this is not a bug in the preprocessor!) to (b+2*b+2), which will be evaluated as (b+(2*b)+2) since multiplication has higher precedence than addition.
This can be solved by defining SQR like:
Code:
#define SQR(x) ((x)*(x))
More generally, always put your arguments in parentheses each time they're used.
Note that there's still a flaw in this macro - a call to SQR(b++) would be expanded to ((b++)*(b++)), which is clearly not what you want. When you use a macro, you should try and only use each argument once, as it might have side effects.
You can cure this with:
Code:
#include <math.h>
#define SQR(x) pow((x),2)
John G