I know this is a weird question, but I'm trying to find a way to analyze the code written by the user and collect some useful information that may be included in both "if" & "else" part. Suppose I have an if-else statement,
counter = 0;
if( true )
++counter;
else
++counter;
is it possible that I can "enforce ++counter" to work and get "counter = 2" at compiler time? Template? Macro? Any other solution? Thanks in advance!
First of all, `counter' will never be 2. It will always be 1.
I'd say about 90% of current C++ compilers (running in "Release" mode") will recognize the invariant, and generate object code as if you had written:
Most will also go as far as
However, such optimizations are not required by the Standard, so there is no way to "Force" a compiler to do them.
NOTE: The specifications for Java & C# do require compilers for those languages to recognize the invariant to do elide the
if()
)