Valar Morghulis Valar Morghulis -4 years ago 123
C++ Question

weird error "expression result is unused" in c++

I have some code like:

double calculate_self_term(double area) {
double corr = 2.0 * sqrtpi / sqrt(area);
return calculate_reciprocal(0, 0, 0) + self_energy + corr;
}


where
self_energy
is defined at the beginning:

#define self_energy -2.0 * alpha / sqrtpi;


Then I got an error:
expression result is unused for the variable
corr
. As in the picture:
enter image description here

I could not understand why
corr
is not used in this line.

First I thought it was a bug for the IDE (Clion), then I found the same error report when I using other IDE.

Actually the
corr
is not used, because when I change it to:

return calculate_reciprocal(0, 0, 0) + corr + self_energy;


They give DIFFERENT results!!!

Is it because we can not add variables after some
#Define
term?

Answer Source

Don't use macros for such things.

With your definition:

#define self_energy -2.0 * alpha / sqrtpi;

Your code substitutes to:

return calculate_reciprocal(0, 0, 0) + -2.0 * alpha / sqrtpi; + corr;

At which point the issue should be obvious - you have this +corr expression statement, after your return statement, which is doing nothing.

If you didn't use the macro, you wouldn't have run into such an issue. Don't use macros for such things. This should probably just be a function:

constexpr auto self_energy(double alpha) { return -2.0 * alpha / sqrtpi; }
// ...
return calculate_reciprocal(0, 0, 0) + self_energy(alpha) + corr;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download