compiler optimization and reference vars

Aug 23, 2011 at 8:46am

Hi. I often use reference variables to rename my longer, global variables.

e.g. double& X = SomeLongVariableName;
result = -X*X + X;

Is this a bad idea? Is there a reason the compiler would not optimize these away?
Aug 23, 2011 at 9:08am
I find your convention very funny.

e.g. double& X = SomeLongVariableName;

.... 1 page of code later ....

result = -X*X + X; //who will now know what X is ? :O
Aug 23, 2011 at 12:26pm
That's something you can do. That's totally ok. As long as renaming does not lead to confusion. Often its better to keep long variable names for more clarity. If its a very local variable like in an inner loop and you just want to shorten your code and make it more readable, go ahead.

Good compilers will optimize the variable away in release mode.

Hopefully by global variable you don't mean real global variable, that are globally accessible by everything. That is legal, but bad programming style, and therefore to be avoided, if possible.
Aug 24, 2011 at 3:11am
Blah.

Short variable names are just as unreadable as long ones. If the long ones are too long, find shorter names for them.
Aug 24, 2011 at 9:57am
@ Ralph: does your "bad programming style if using global variables" include global constants as well...so would it be bad style to do like so:

 
static const double identMatrix[3][3] = {{1,0,0},{0,1,0},{0,0,1}};


i think it's pretty much clear what a identMatrix is, and it's not "accessible" for writing either...I'm no programmer though and don't know what drives you nuts when encountered....

BTW: does the compiler do code optimisation in a way like pre-performing calculations (if all values are known during compilation)...?
Example:
 
const int something = 10 * 5;


does the compiler perform this calculation or is it performed during runtime??

ZED
Aug 24, 2011 at 10:26am
does your "bad programming style if using global variables" include global constants as well...so would it be bad style to do like so:

Global constants don't have the same problems as global variables, so they're generally fine (although they should be inside a namespace). Still, often it makes sense to make constants static members of a class.

does the compiler do code optimisation in a way like pre-performing calculations (if all values are known during compilation)...?

Yes, it does. It's a very basic optimization called constant folding.

Topic archived. No new replies allowed.