Skip to content

Commit ef5adec

Browse files
authored
Update 2025-11-30-comptime-c-functions.md
1 parent 9cb692d commit ef5adec

1 file changed

Lines changed: 5 additions & 4 deletions

File tree

_posts/2025-11-30-comptime-c-functions.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,18 +29,19 @@ Here is how it is achieved in C:
2929

3030
This optimization requires stack-allocated buffers with constant addresses. Heap allocation breaks the optimization, because the compiler can't trace memory operations through dynamic allocations.
3131

32-
The only legitimate use-case I can think of for this technique is generating lookup tables at compile-time.
32+
The only legitimate use-case I can think of for this technique is generating lookup tables at compile-time, as functions like `sin()` also get optimized away.
3333

3434
[Link-time optimization](https://en.wikipedia.org/wiki/Interprocedural_optimization) with `-flto` should allow Clang and GCC to perform these optimizations even when the code is split across several object files.
3535

3636
# Generic Stack
3737

3838
Clang and GCC require `-O1`.
3939

40-
Copy of the code on [Compiler Explorer](https://godbolt.org/z/r77c6hf8d):
40+
Copy of the code on [Compiler Explorer](https://godbolt.org/z/Y86szvfeG):
4141

4242
```c
4343
#include <assert.h>
44+
#include <math.h>
4445
#include <stdbool.h>
4546
#include <stddef.h>
4647
#include <stdint.h>
@@ -105,14 +106,14 @@ int main(void) {
105106
stack_init(&s, buffer, sizeof(Pair), 100);
106107

107108
Pair p1 = {.a = 10, .b = 20};
108-
Pair p2 = {.a = 111, .b = 222.0};
109+
Pair p2 = {.a = 111, .b = sin(222.0)}; // sin() is optimized away!
109110

110111
assert(stack_push(&s, &p1) == SUCCESS);
111112
assert(stack_push(&s, &p2) == SUCCESS);
112113

113114
Pair out2;
114115
assert(stack_pop(&s, &out2) == SUCCESS);
115-
assert(out2.a == 111 && out2.b == 222.0);
116+
assert(out2.a == 111 && out2.b == sin(222.0));
116117

117118
Pair out1;
118119
assert(stack_pop(&s, &out1) == SUCCESS);

0 commit comments

Comments
 (0)