0
#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);
    }
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Emir Kutlugün
  • 349
  • 1
  • 6
  • 18

2 Answers2

2

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);
}
cocool97
  • 1,201
  • 1
  • 10
  • 22
2

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);
0___________
  • 60,014
  • 4
  • 34
  • 74
  • 1
    Macros substitute preprocessor tokens, not text. If they substituted text, they could form new preprocessor tokens, but they cannot (without the `##` operator). E.g., with text replacement, `#define foo(x) -x` / `y = 3-foo(x);` would become `y = 3--x;`, which is an error since `--` cannot be applied to `3`. But it does not become that; it becomes effectively `y = 3- -x;`. – Eric Postpischil Mar 01 '20 at 13:14
  • @EricPostpischil bare in mind that the OP is a very beginner. I was considering if I shuold write text or token, but at this level "token" (IMO) adds another confusion. – 0___________ Mar 01 '20 at 13:20
  • 2
    Simplification is okay. False statements are not. – Eric Postpischil Mar 01 '20 at 13:20