2

I ran it through Code::Blocks and it shows me the final answer 1. How is TWO then replaced in the " i = i-2*TWO" statement and why is like that?

The code is part of a homework exercise I'm trying to solve/understand:

#include <stdio.h> 
    #define  ONE    1
    #define  TWO    ONE + ONE
    int main(void) { 
        int i = 2;
        i = i - 2 * TWO;
        printf("%d\n", i);
        return 0; 
    }
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
painkiller
  • 149
  • 6
  • 1
    Think like a preprocessor! – Eugene Sh. Sep 30 '19 at 17:05
  • It will be replaced as `i = i - 2*1 + 1`, which yields result 1. – kiran Biradar Sep 30 '19 at 17:08
  • 1
    This is a simple one, but for more complex macros, some (or maybe all) compilers have an option to save the pre-processed code file. For example: [How do I see a C/C++ source file after preprocessing in Visual Studio?](//stackoverflow.com/q/277258) – 001 Sep 30 '19 at 17:10

2 Answers2

5

Just make the substitution yourself.

i = i - 2 * TWO;

is

i = i - 2 * ONE + ONE;

So you have

i = 2 - 2 * 1 + 1;

So i will have the value 1.

If you want to get the result equal to -2 then rewrite the macro like

#define  TWO    ( ONE + ONE )
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
2

You can see what the compiler sees as final expression by running gcc -E <filename.c>. That should help in understanding why the result is 1.

Ranganatha
  • 113
  • 4