diff options
| author | David Faulkner <[email protected]> | 2026-08-07 23:40:47 -0500 |
|---|---|---|
| committer | David Faulkner <[email protected]> | 2026-08-07 23:40:47 -0500 |
| commit | b3e9e62599532050fc776c5e8f076915b56c2235 (patch) | |
| tree | af252346106a61b18cc6fc6fdbd32e962d096f1c /lifetime.c | |
Import official C23 code examples for Modern C (Jens Gustedt, 2024)HEADupstream-importmain
- Add official C source files, Makefile, c23-fallback.h, and LICENSE
- Update README.md with study mirror notice
Diffstat (limited to 'lifetime.c')
| -rw-r--r-- | lifetime.c | 89 |
1 files changed, 89 insertions, 0 deletions
diff --git a/lifetime.c b/lifetime.c new file mode 100644 index 0000000..ed12c10 --- /dev/null +++ b/lifetime.c @@ -0,0 +1,89 @@ +#include <stdio.h> +#include "c23-fallback.h" + +void fgoto(unsigned n) { + unsigned j = 0; + unsigned* p = nullptr; + unsigned* q; + AGAIN: + if (p) printf("%u: p and q are %s, *p is %u\n", + j, + (q == p) ? "equal" : "unequal", + *p); + q = p; + p = &((unsigned){ j, }); /*@\label{lifetime_compound_literal}*/ + ++j; + if (j <= n) goto AGAIN; +} + +void fgotoblock(unsigned n) { + unsigned j = 0; + unsigned* p = nullptr; + unsigned* q; + AGAIN: // Using a compound statement creates a new object at each iteration. + { // A good modern compiler should complain that it is uninitialized. + if (p) printf("%u: p and q are %s, *p is %u\n", + j, + (q == p) ? "equal" : "unequal", + *p); + q = p; + p = &((unsigned){ j, }); + ++j; + if (j <= n) goto AGAIN; + } +} + +__attribute__((noinline)) +void ffor1(void) { + unsigned j = 1; + printf("%u: p and q are %s, *p is %u\n", + j, + "unequal", + j-1); +} + +__attribute__((noinline)) +void fforn(unsigned n) { + ffor1(); + for (unsigned j = 2; j <= n; ++j) { + printf("%u: p and q are %s, *p is %u\n", + j, + "equal", + j-1); + } +} + +void ffor(unsigned n) { + switch (n) { + case 0: break; + case 1: ffor1(); break; + default: fforn(n); break; + } +} + +void fVLA(unsigned n) { + unsigned volatile j = 0; + unsigned* p = nullptr; + unsigned* q; + AGAIN: + { + if (p) printf("%u: p and q are %s\n", + j, + (q == p) ? "equal" : "unequal"); + q = p; + unsigned VLA[j+1]; + for (unsigned i = 0; i <= j; ++i) + VLA[i] = j; + p = VLA; + ++j; + if (j <= n) goto AGAIN; + } +} + + + +int main(int argc, [[maybe_unused]] char* argv[]) { + fgoto(argc+1); + fgotoblock(argc+1); + ffor(argc+1); +} |
