Sign in to follow this  
Orione

C2440 - VS2005 - C++

Recommended Posts

Simplified example:
01: #define NULL 0
02: 
03: int main(int argc, char* argv[]) {
04:   bool   value = true;
05: 
06:   float *pTest = NULL;
07:
08:   pTest = (true  ? NULL : NULL);
09:   pTest = (false ? NULL : NULL);
10:   pTest = (value ? NULL : NULL);
11:
12:   return 0;
13: }


Build Output: main.cpp(10) : error C2440: '=' : cannot convert from 'int' to 'float *' Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast What's going on? Why does it work with bool const while it fails on bool value? Any hint is welcome!

Share this post


Link to post
Share on other sites
We found 2 ways to solve the problem.
Our hypothesis is that the error is due to compiler optimization but a documented explanation would be great if anyone can point a document.

Solution 1:

01: #define NULL 0
02:
03: int main(int argc, char* argv[]) {
04: const bool value = true; // Const variable is optimized by compiler
05:
06: float *pTest = NULL;
07:
08: pTest = (true ? NULL : NULL);
09: pTest = (false ? NULL : NULL);
10: pTest = (value ? NULL : NULL);
11:
12: return 0;
13: }




01: #define NULL 0
02:
03: int main(int argc, char* argv[]) {
04: bool value = true;
05:
06: float *pTest = NULL;
07:
08: pTest = (true ? NULL : NULL);
09: pTest = (false ? NULL : NULL);
10: pTest = (value ? reinterpret_cast<float*>(NULL) : reinterpret_cast<float*>(NULL)); // Explicit cast help compiler
11:
12: return 0;
13: }

Share this post


Link to post
Share on other sites
The C++ standard states that any integral constant expression rvalue of integer type that evaluates to 0 can be used as a null pointer constant. When you have true ? NULL : NULL, that expression is an integer constant expression, since all those values are known at compile time. However, value ? NULL : NULL is not an integer constant expression, since value isn't known at compile time.

Share this post


Link to post
Share on other sites
You don't need to go all-out with reinterpret_cast to solve this. In fact, it's probably dangerous (the whole reason the problem exists in the first place is that a "null" pointer does not necessarily consist of all clear bits on all platforms). static_cast would be my pick (using "constructor syntax" doesn't work for pointers IIRC, and a C-style cast is, well, a C-style cast). Or better yet, keep a const null pointer around so you can use it in these expressions. :)

Also, you shouldn't need to #define NULL yourself.

On the bright side, C++0x is supposed to fix this mess with the new 'nullptr' keyword.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this