Is there a way to tell the compiler that you know that the value of a particular variable should be in a certain range at a certain point in the code to help the compiler optimize? I am writing a library that allows you to find out the range of some variables during compilation, and it would be great if it somehow passed this information to the compiler so that the compiler could use it for optimization. I would like to add support for any compilers where it will work, even if it cannot be used to work for everyone (it looks like some compilers can have it as an extension, but I don’t have any). I know that I can write something like this:
if(x < COMPILE_TIME_MIN or x > COMPILE_TIME_MAX) return; // compiler will assume for code below that x is in range COMPILE_TIME_MIN..COMPILE_TIME_MAX
But this is a runtime check. Maybe there is some kind of trick to get the compiler to make a range assumption without such a check?
Any such "hint" will be specific to the compiler.
As an example, Visual C ++ allows you to give such a hint using an __assumeinternal one .
__assume
(Other compilers may also provide such built-in functions, but I am not familiar with other compilers to provide additional information. Consult your compiler documentation if you are interested.)
, gcc __builtin_expect, , likely unlikely, . . , , __builtin_expect gcc (. ), likely unlikely .
__builtin_expect
likely
unlikely
- ++, , , ; "" - assert s, :
assert
assert(x > COMPILE_TIME_MIN); assert(x < COMPILE_TIME_MAX);
, " " , .
, , - , char - COMPILE_TIME_MIN. , .
COMPILE_TIME_MIN
, , , , , . , , "" . , , .