Why the following code does not generate a warning in MSVC

I have a section of code that can be summarized as follows:

void MyFunc() { int x; ' ' x; ' ' } 

I would think that just referring to a variable without changing it in any way or using its value should generate a warning in any case. In VS2003, it does nothing, and I need to pick it up.

I understand that this does not affect execution, but since it is a piece of code that does nothing, and the programmer undoubtedly intended to do something, why is it not marked?

Similarly, would you expect x = x to be a warning?

Edit: The amended question as this is a good candidate for a warning, but not a mistake. The answers show that other compilers are better off. Try VS2008 later and post the result.

+6
c ++ compiler-warnings
source share
4 answers

You need to use the best compiler :-) Compiled with the -Wall and -pedantic flags, the GCC C ++ compiler gave this code:

 int main() { int x = 0; x; } 

produces this diagnostic:

 ma.cpp:3: warning: statement has no effect 
+1
source share

Such code may occur in a template class for metaprogramming purposes. For example, it might be some kind of check if x is available from the current context. Yes, this does not affect the execution result, but it affects the compilation result; this may be useful for methods like SFINAE .

It doesn't seem to help compilation either. Funciton bodies do not count on choosing the right template to call a function. To check accessibility within a class, you must use the using statement for dependent names; this using statement itself is an accessibility check.

So the code is x; really has no effect.

+1
source share

You are expecting a warning if you do not draw an expression on void, i.e.

 void MyFunc() { int x; (void)x; } 

What warning level did you set?

+1
source share

Both statements with one variable (for example, x; ) and self-determination (for example, x = x ) are valid C ++ code, so the compiler can’t designate them as errors, but a good compiler, of course, can give a warning about that they have no effect and may be errors of the programmer.For example, the g ++ compiler gives a warning “instruction has no effect” for x;.

0
source share

All Articles