Showing posts with label Compiler Warnings. Show all posts
Showing posts with label Compiler Warnings. Show all posts

BOOL to bool

I faced a very simple problem the other day. The compiler started generating a warning:

warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning)

The reason being that because I was including some Windows file that included windef.h. In windef.h, it says: typedef int BOOL;

What I was trying to do was to cast that BOOL to bool. Of course we can suppress the warning easily by the #pragma directives as discussed earlier but there has to be a better and a simpler way. Then it clicked, how about a simple != 0 comparison. Here is the sample code:



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

using namespace
std;

int
main()
{

BOOL someVal = 1;

bool
firstApproach = someVal; //Generates warning C4800
cout<<"firstApproach = "<<firstApproach<<endl;

bool
secondApproach = (someVal != 0); //No Warning
cout<<"secondApproach = "<<secondApproach<<endl;

return
0;
}

Suppress Compiler Warning using #pragma

Ocassionally the compiler can throw out warnings which may be informative to you but you do not want others to see. You can use a #pragma directive to suppress the warnings. An example of the code below:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy

//This example shows how to suppress warnings using #pragma

#include<iostream>



using namespace
std;



class
error

{


public
:

error(string s)

{


info = s;

}


private
:

error();

string info;

};




#pragma warning( disable : 4290 )



int
someFunc(void) throw (error)

{


return
1;

}




#pragma warning( default : 4290 )



int
someOtherFunc(void) throw (error)

{


return
1;

}




int
main()

{




return
0;

}




Here, for 'someOtherFunc', the compiler will generate a warning:


warning C4290: C++ exception specification ignored except to indicate a function is not __declspec(nothrow)


but a similar warning for 'someFunc' wont be generated because we have already suppressed it using the #pragma.


Check out this stream