Home > Back-end >  using definitions in c inefficient?
using definitions in c inefficient?

Time:05-09

is using definitions in c like this:

#define C1 42
#define C2 10
#define finalC C1 * C2

inefficient as this code will be ALWAYS run during run-time even though the calculation might not be needed?

CodePudding user response:

as this code will be ALWAYS run during run-time even though the calculation might not be needed?

The multiplication will most likely not be executed at run-time. For example, this short function:

#define C1 42
#define C2 10
#define finalC C1 * C2

int foo() { return finalC; }

may compile into:

foo():
        push    rbp
        mov     rbp, rsp
        mov     eax, 420
        pop     rbp
        ret

and that's without any optimization flags!

The macro expansion happens before the compiler processes the code; and it is allowed, and tends to, evaluate constant expressions.

PS - The compiler used was GCC 11.3 and the target architecture is x86_64.

CodePudding user response:

No reasonable compiler will multiple 42 by 10 for this code at run-time. The product, 420, will be computed during compilation (unless optimized out because it is not even needed in the final program).

The macro definitions and replacements are evaluated during program translation, not while the program is running.

CodePudding user response:

The #define is a instruction to the pre-processor which historically was evaluated before the compilation of C. This can be used to substitute in values or other constructs before compilation gets to the C grammar. Why assume that #define would bypass compiler optimization? The compiler and optimizer would still see 40 * 10

  •  Tags:  
  • c
  • Related