Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Is there a use case for such a macro, or is it just a puzzle for its own sake?


I use something similar in a container library to warn the user if he or she supplies an argument with potential side effects to a macro that evaluates it multiple times:

https://github.com/JacksonAllan/CC/blob/42a7d810274a698dff87...

Specifically, if (arg)==(arg) is not a constant expression, then it could have side effects.

However, this mechanism does generate some annoying false positives, as shown below:

  // Create a map with int keys and values that are vectors of floats:
  map( int, vec( float ) ) our_map;
  init( &our_map );
  
  // Create a vector of floats:
  vec( float ) our_vec;
  init( &our_vec );
  push( &our_vec, 1.23f );
  
  // Insert the vector into the map.
  insert( &our_map, 456, our_vec );
  
  // Generates a warning because get checks its first argument for side
  // effects and the compiler can't tell that the first argument of the
  // outermost get has none:
  printf( "%f", *get( get( &our_map, 456 ), 0 ) );
  
  // The "proper", albeit cumbersome, way to achieve the same thing without a
  // warning:
  vec( float ) *itr = get( &our_map, 456 );
  printf( "%f", *get( itr, 0 ) );


The use case that comes to mind is doing manual compile time optimization based on macro arguments. E.g. you have some assembly block that is fast but requires some immediate arguments, and you have a fallback path for the dynamic case, and you want to determine which one to call at compile time based on whether the arguments are constants or not.


I've seen something related, which returned a bool instead of failing compilation, be used to switch between a path the optimiser could inline and some assembly. You could probably use this to make sure it was always inlined.


If you're writing code that needs to behave deterministically and not have side effects, you could use this to make violations of determinism/side-effect-freeness fail fast, I guess?


Probably not. The Linux kernel has one.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: