8

Basic question

#define A 5
#define B 10

#define C (A*B)


int var;
var = C;

so here how macros will be expanded, Is it

var = (5*10)

or

var = (50)

My doubt is on the macro expansion. If macros has some calculations (*,-,/,+) on all constant,then will marco is just a in line expansion or it will evaluate the result and post it

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Ni3 B
  • 81
  • 1
  • 1
  • 2

7 Answers7

5

Macro expansion is always just a textual transform of the input source code. You should be able to see the code after the pre-processor (the part of the compilation that does the macro expansion) is done; this text is what the compiler proper then works on.

But many compilers do "constant folding" optimization during compilation, that will optimize 5 * 10 to 50 so that it doesn't need to be calculated at runtime.

unwind
  • 391,730
  • 64
  • 469
  • 606
4

May be its preprocessor dependent. Since compiler does the optimization, the preprocessor may be only doing substitution.

My gcc version i686-apple-darwin10-gcc-4.2.1 is showing it as option 1

var = (5*10)

you can use -E flag option to check

like

gcc -E test.c
M S
  • 3,995
  • 3
  • 25
  • 36
3

Macros are just textual replacement wherein the pre-compiler just replaces the macro with its defined value. So once the macro is replaced by its definition the compiler will evaluate those operations. Further compilers may optimize how they treat expressions such as (5*10) compilers follow the As-If rule of optimization wherein they might directly replace (5*10) by 50 since that does not change the observable behavior of your program.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
2

The output of the preprocessor will be (5*10). It is the responsibility of the compiler to perform calculation, or in this case constant-fold, the expression.

Lindydancer
  • 25,428
  • 4
  • 49
  • 68
0

Macros are used to optimize the code, by reducing the amount of work that needs to be done at compile time. Here it reduced the work of run time by replacing 5*10 by 50, where both the result are same. It performs the mathematical operations by BODMAS method. eg: #define MULTIPLY(a, b) a*b MULTIPLY (10+2,6+5) Result is 10+2*6+5 = 27

Amal lal T L
  • 400
  • 5
  • 20
0

The macro is expanded to var=(5*10) by the precompiler

However the compiler almost certainly optimises this to be equivalent var=50 for any modern compiler.

You should be able to set the compiler to output the precompiled code so that you can see the macro expansions.

Elemental
  • 7,365
  • 2
  • 28
  • 33
0

it will be (5*10) after the macro expand, but after that, the compiler will optimize it with 50.

zchenah
  • 2,060
  • 16
  • 30