andersch.dev

<2024-07-03 Wed>

GNU C Extensions

GNU C extends the C langauge with several features that are not standard compliant. However, they are supported by GCC, Clang, and any compiler that defines the macro __GNUC__. The compiler switch -pedantic will warn about the usage of these extensions.

Statement Expressions

GNU C (and C++) has an extension for having statements and declarations inside an expression:

// computes expressions a and b only once
#define max(a,b) ((a) > (b) ? (a) : (b))
#define max_safe(a,b) ({int _a = (a), _b = (b); _a > _b ? _a : _b; })

int a = 4, b = 4;
printf("Normal macro: %i\n", max(++a, b));
a = 4, b = 4;
printf("State expr:   %i\n", max_safe(++a, b));

This extension is implemented on:

  • gcc, g++, clang, clang++
  • clang-cl.exe, clang.exe, clang++.exe
  • tcc

Resources