3 ms·
Is there a use case for such a macro, or is it just a puzzle for its own sake?
by re 1y ago
Is there a use case for such a macro, or is it just a puzzle for its own sake?
- uecker 1y agoProbably not. The Linux kernel has one.
- apple1417 1y agoI'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.
- kevingadd 1y agoIf 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?
- variadix 1y agoThe 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.
- JacksonAllan 1y agoI 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/42a7d810274a698dff87a6cdbecd91e93798afad/cc.h#L1284 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 ) );