SmacL
SmacL

Reputation: 22922

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.

Upvotes: 6

Views: 987

Answers (4)

anon
anon

Reputation:

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

Upvotes: 1

P Shved
P Shved

Reputation: 99254

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.

Upvotes: 1

Thomas Padron-McCarthy
Thomas Padron-McCarthy

Reputation: 27632

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;.

Upvotes: 0

Paul R
Paul R

Reputation: 212929

You'd expect a warning unless you cast the expression to void, i.e.

void MyFunc()
{
   int x;

   (void)x;  

}

What warning level do you have set ?

Upvotes: 1

Related Questions