#define x 10 + 5
int main(){
int a = x*x;
printf("%d",a);
}
Can someone explain the difference between these codes? first output is 65 and second one is 225:
#define x 15
int main(){
int a = x*x;
printf("%d",a);
}
#define x 10 + 5
int main(){
int a = x*x;
printf("%d",a);
}
Can someone explain the difference between these codes? first output is 65 and second one is 225:
#define x 15
int main(){
int a = x*x;
printf("%d",a);
}
Everything is related to the priority of operators in mathematics and in C.
In the first case, x is replaced by 10 + 5 so x*x is replaced by 10 + 5 * 10 + 5, which equals to 65.
As suggest in comments, you should use parenthesis to avoid this problem.
#define x (10 + 5)
int main(){
int a = x*x;
printf("%d",a);
}
Macros are not functions or methods. It is just textual (actually tokens, but for the sake of simplicity I will not get deeper into it) replacement done before the actual C compilation.
lets consider
#define x 10 + 5
int a = x*x;
if we replace x by the 10 + 5
int a = 10 + 5*10 + 5;
it is probably not something you want. If we add the parenthesises:
#define x (10 + 5)
int a = x*x;
the expansion will be:
int a = (10 + 5)*(10 + 5);