Reputation: 93
My question may be too easy, but I have not found the answer, sorry for that.
if I have some code like this:
...
#define N 6
...
float a, b;
...
a = 2.0 * 3 * N * b;
...
then, after compilation, will this code become something like this?
...
a = 36.0 * b;
...
In other words, the constant part will be calculated at compile time, right?
Thank you in advance.
Upvotes: 3
Views: 1602
Reputation: 9494
Here is sample code,
#include <stdio.h>
#define val 10
int main()
{
int b = 100;
int k = (5 * val) + b;
//int k = (5 * 25) + b;
return 0;
}
val is replaced 10 during pre-processing,
cpp ss.c
gives me
int main()
{
int b = 100;
int k = (5 * 10) + b;
return 0;
}
If we look at assembly(gcc -S ss.c),
.file "ss.c"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movl $100, -8(%rbp)
movl -8(%rbp), %eax
addl $50, %eax //5 * 10 calculated !!!
movl %eax, -4(%rbp)
movl $0, %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3"
.section .note.GNU-stack,"",@progbits
so constants are calculated at compile time itself in gcc.
Upvotes: 0
Reputation: 62106
Most likely, but not guaranteed.
You can try and look at the disassembly of your program (either in a debugger, or in a disassembler or use a compiler switch (if available) to produce assembly code from your C code).
Upvotes: 4