Wednesday 2 February 2011

Consequences of Ignoring Compiler Warnings

Though this is a fictional program that I have picked up from here, I have seen similar problems in real life.

Lets say my program (below) was expected to return this


but instead returned:

Program as follows:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

class
Bclass
{

public
:
Bclass() {}
virtual
void func()
{

cout<<"In Bclass::func()"<<endl;
}
};


class
Dclass : public Bclass
{

public
:
Dclass() {}
virtual
void func()
{

cout<<"In Dclass::func()"<<endl;
Bclass:func();
}
};


int
main()
{

Dclass d;
d.func();
//...
return 0;
}



The clue of the problem was given by the compiler that generated the following warning:

main.cpp(23) : warning C4102: 'Bclass' : unreferenced label

pointing to the line

Bclass:func();

The problem lies in the fact that due to a single : rather than :: the line above is being treated as label and since its an unreferenced label it goes back to the start of the same function.

You can read the complete discussion here. Make sure to check the warnings the next time your program behaves unexpectedly.

No comments:

Post a Comment