简体   繁体   中英

Why does the following code not generate a warning in MSVC

I have a section of code that can be summarised as follows;

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

I would have thought that simply referencing a variable, without modifying it in anyway or using its value in anyway should generate a warning. In VS2003 it does neither, and it I need lint to pick it up.

I realise it doesn't effect execution, but since it is a piece of code that does nothing, and the programmer doubtless intended to do something, why is it not flagged?

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

Edit: Modified question, as this constitutes a good candidate for a warning, but is not an error. Replies suggest this is handled better with other compilers. Will try out VS2008 later and post result.

Such code might occur in a template class for metaprogramming purposes. For example, it might be some kind of a check whether x is accessible from the current context. Yes, it doesn't affect the result of execution , but it does affect the result of compilation ; this might be of aid to techniques like SFINAE .

It seems, that it's of no help to compilation either. Funciton bodies don't count for choosing the proper template for a function call. And to check accessibility within a scope of a class, you have to use using operator for dependent names; this using operator itself being an accessibility check.

So, the code x; really has no effect.

You'd expect a warning unless you cast the expression to void, ie

void MyFunc()
{
   int x;

   (void)x;  

}

What warning level do you have set ?

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

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

produces this diagnostic:

ma.cpp:3: warning: statement has no effect

Both single-variable statements (such as x; ) and self-assignment (such as x=x ) are valid code in C++, so the compiler can't flag them as errors, but a good compiler is of course allowed to give a warning that they don't have any effect, and might be mistakes by the programmer. For example, the compiler g++ gives the warning "statement has no effect" for x; .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM