Compile-time calculation: Difference between revisions

Simpler C code
(Simpler C code)
Line 93:
 
This and similar macro libraries are very demanding on the preprocessor, and will require a standards-compliant implementation such as GCC.
 
===C (simpler version)===
This is a simple version, showing that 10! was computed at compile time:
<lang c>#include <stdio.h>
const int val = 2*3*4*5*6*7*8*9*10;
int main(void) {
printf("10! = %d\n", val );
return 0;
}</lang>
 
{{out}}<pre>10! = 3628800</pre>
 
{{asm from compiler}}
<pre>$ gcc 10fact.c -S
$ cat 10fact.s
.file "10fact.c"
.globl val
.section .rdata,"dr"
.align 4
val:
.long 3628800
.def __main; .scl 2; .type 32; .endef
.LC0:
.ascii "10! = %d\12\0"
.text
.globl main
.def main; .scl 2; .type 32; .endef
.seh_proc main
main:
pushq %rbp
.seh_pushreg %rbp
movq %rsp, %rbp
.seh_setframe %rbp, 0
subq $32, %rsp
.seh_stackalloc 32
.seh_endprologue
call __main
movl $3628800, %eax # critical line showing the compiler computed the result.
movl %eax, %edx
leaq .LC0(%rip), %rcx
call printf
movl $0, %eax
addq $32, %rsp
popq %rbp
ret
.seh_endproc
.ident "GCC: (GNU) 4.9.3"
.def printf; .scl 2; .type 32; .endef
</pre>
 
=={{header|C++}}==
Anonymous user