top | item 31225426

(no title)

Ne02ptzero | 3 years ago

Side topic: Didn't we have a is_const_eval equivalent in C? I seem to remember a dark magic macro doing precisely that on the lkml somewhere, but can't find it.

discuss

order

mhh__|3 years ago

You might be able to do something truly arcane using GCC extensions and maybe the __attribute((error))__ thing but realistically it either won't compile or you won't notice unless it's too slow.

The compiler constant folds fairly effectively anyway.

rwmj|3 years ago

This is what qemu uses:

  #define QEMU_BUILD_BUG_ON(x) \
    typedef char qemu_build_bug_on[(x)?-1:1] __attribute__((unused));
So you can write stuff like:

  QEMU_BUILD_BUG_ON(sizeof (struct foo) == 128);
(for example if the struct is used for some network protocol and so it must be 128 bytes long).

pm215|3 years ago

We've switched to _Static_assert() now we can assume all our compilers support it:

   #define QEMU_BUILD_BUG_MSG(x, msg) _Static_assert(!(x), msg)

   #define QEMU_BUILD_BUG_ON(x) QEMU_BUILD_BUG_MSG(x, "not expecting: " #x)

einpoklum|3 years ago

There is no compilation-time evaluation of functions and statements in C. You have constants, which can be expressions, but that's about it. Oh, and macros of course.

compile-time evaluation was introduced in C++11 and expanded in subsequent versions of the language standard.

qalmakka|3 years ago

Also, `const` values in C are not really evaluated at compile time, because they have by default external linkage so they are not really "constant", they are more like "readonly" or 'let' in Rust. They are always loaded from memory, and that's why #define is still king in C.

Doing

  const int X = 33;
  
  // ...
  
  void something() {
      int arr[X] = ...
  }
works in both C and C++, but with a catch: in C++, X is evaluated at compile time (it has internal linkage), while in C this works only after C99 because it's actually a VLA.

uecker|3 years ago

What do you want to use it for? C++ uses it for the compile-time programming together with templates. Essentially C++ evolves into a language where you write a program that gets interpreted at compile-time to produce some code that then gets compiled. But I am not sure this is a good idea. It adds a lot of complexity, places many responsibilities that belongs into a compiler onto library writers, increases compilation time a lot, and - with all template expansion - causes a lot of bloat that hurts performance. It also makes debugging interesting. But it looks really good in microbenchmarks because you can create optimal code for special cases easily, I just do not see how this translates into real world performance.

jcelerier|3 years ago

If it's not in the language it will be in separate preprocessors, which will all be strictly worse.