One possible approach is to put it in a symbolic mathematical program (like Mathematica or Maple) and make this simplification for you. He will do this regardless of whether they are constants or not.
The disadvantage is that you need to convert the code to another language. (Although this can be basically copy and paste if the syntax is similar.) Also, it can be dangerous if you expect some integer types to overflow with a certain size. Symbolic math programs do not care and optimize it according to "math". The same goes for floating point rounding errors.
In your example, if you enter this in Mathematica:
a = 3; b = 4; c = a + b; d = c; c
Will output this in Mathematica:
7
Of course, you cannot just copy and paste because it is a different language and different syntax, but it is the best that I have in mind for your question. I myself use Mathematica to simplify expressions and other maths before throwing it into C / C ++.
For a more complex example involving unknowns:
Original C Code:
int a = 3 + x*x; int b = 4 + y*y; int c = a + b - 7 + 2*x*y; int d = c;
Enter this into Mathematica (which still basically copies and pastes):
a = 3 + x*x; b = 4 + y*y; c = a + b - 7 + 2*x*y; d = c; FullSimplify[c]
Conclusion:
(x + y)^2
What converts back to the following C code:
d = (x + y) d = d * d;
This is obviously much simpler than the source code. In general, symbolic programs even process non-trivial expressions and will do the same (or even better) than any internal compilers.
The final downside is that symbolic math programs like Mathematica or Maple are not free and quite expensive. SAGE is an open source program, but I heard that it is not as good as Mathematica or Maple.
source share