Counter at Compile TIme

347 Views Asked by At

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!

1

There are 1 best solutions below

0
On

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:

counter = 0;
++counter;

Most will also go as far as

counter = 1;

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())