473,413 Members | 2,051 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,413 software developers and data experts.

When to use null and when to use static_cast<some_pointer_type>(0)?

I see some code use static_cast<some_pointer_type>(0) instead of NULL
to describe null pointer. I'm wondering what is the pros and cons of
each way. Is there any reason why we should one verses the other.

Mar 31 '06 #1
19 3688
Pe*******@gmail.com wrote:
I see some code use static_cast<some_pointer_type>(0) instead of NULL
to describe null pointer. I'm wondering what is the pros and cons of
each way. Is there any reason why we should one verses the other.


What code does it the complex way? Could you post a sample?

NULL is magic, and should generally always appear as the constant "NULL".
Maybe you saw code that upgraded from C, which used (void*)0.

NULL is magic because a constant 0, in C++, always freely converts to any
pointer type, just as typesafely as if you had put an elaborate cast on it.
Don't.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Mar 31 '06 #2

Phlip wrote:
Pe*******@gmail.com wrote:
I see some code use static_cast<some_pointer_type>(0) instead of NULL
to describe null pointer. I'm wondering what is the pros and cons of
each way. Is there any reason why we should one verses the other.
What code does it the complex way? Could you post a sample?


template <class T>
class Nil {
public:
operator T* () { return static_cast<T*>(0); }
};

template <class T>
void Delete(T*& x) {
delete x;
x = Nil<T>();
}

The above is the code fragment.

In general, NULL is preferred, right?

NULL is magic, and should generally always appear as the constant "NULL".
Maybe you saw code that upgraded from C, which used (void*)0.

NULL is magic because a constant 0, in C++, always freely converts to any
pointer type, just as typesafely as if you had put an elaborate cast on it.
Don't.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!


Mar 31 '06 #3

Pe*******@gmail.com wrote:
Phlip wrote:
Pe*******@gmail.com wrote:
I see some code use static_cast<some_pointer_type>(0) instead of NULL
to describe null pointer. I'm wondering what is the pros and cons of
each way. Is there any reason why we should one verses the other.


What code does it the complex way? Could you post a sample?


template <class T>
class Nil {
public:
operator T* () { return static_cast<T*>(0); }


That cast is invalid and, luckily, unnecissary.

You can't static_cast between unrelated types. An int and a T* are
totally unrelated. Luckily enough, 0 is magic in that it can be any
pointer as well as an integral. So, that is just calling a static cast
from T* to T*...if it wasn't the code would not compile.

What the original coder probably intended was a reinterpret cast.
However, since the static cast worked it shows that it is not necissary
to perform any casting at all.

Mar 31 '06 #4
* Noah Roberts wrote, on 31/03/2006 22:53:
Pe*******@gmail.com wrote:
template <class T>
class Nil {
public:
operator T* () { return static_cast<T*>(0); }
That cast is invalid


No.

and, luckily, unnecissary.
Yes.
[snip] What the original coder probably intended was a reinterpret cast.


No, that would be invalid. ;-)
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Mar 31 '06 #5
Noah Roberts wrote:
template <class T>
class Nil {
public:
operator T* () { return static_cast<T*>(0); }


That cast is invalid and, luckily, unnecissary.


I want to know why the Nil class is there. If its only purpose is this line

delete x;
x = Nil<T>();

then it is an excessive and unnecessary way to write x = NULL.

Someone may have Template Fever here. ;-)

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Apr 1 '06 #6
Phlip wrote:

Someone may have Template Fever here. ;-)


Unfortunately, a far too common ailment.

--

Pete Becker
Roundhouse Consulting, Ltd.
Apr 1 '06 #7

Pe*******@gmail.com wrote:
I see some code use static_cast<some_pointer_type>(0) instead of NULL
to describe null pointer. I'm wondering what is the pros and cons of
each way. Is there any reason why we should one verses the other.


Consider:

MyStream& operator<<(MyStream&, int);
MyStream& operator<<(MyStream&, const char*);

MyStream m;
m << NULL;
m << static_cast<char*>(0);

HTH
Michiel Salters

Apr 3 '06 #8

Alf P. Steinbach wrote:
* Noah Roberts wrote, on 31/03/2006 22:53:
Pe*******@gmail.com wrote:
template <class T>
class Nil {
public:
operator T* () { return static_cast<T*>(0); }


That cast is invalid


No.

and, luckily, unnecissary.


Yes.
[snip]
What the original coder probably intended was a reinterpret cast.


No, that would be invalid. ;-)


Interesting. How do you figure? Since 0 is an int (except when used
as a pointer, which such added behavior is what renders any cast moot)
I can't think of any static_cast that is valid. In fact g++ pukes when
you try to static_cast but allows the reinterpret_cast through just
fine.

int main()
{
int x = 0;
int *r = reinterpret_cast<int*>(x);
int *p = static_cast<int*>(x);

return 0;
}

g++ stat.cpp
stat.cpp: In function `int main()':
stat.cpp:5: error: invalid static_cast from type `int' to type `int*'
g++ seems to think it is an invalid cast. So do I.

Apr 3 '06 #9

The OP wrote:
> operator T* () { return static_cast<T*>(0); }
Noah Roberts wrote:
That cast is invalid
Alf P. Steinbach wrote:
No.
Noah Roberts:
What the original coder probably intended was a reinterpret cast.


Alf Steinbach:
No, that would be invalid. ;-)


Noah Roberts:
Interesting. How do you figure? Since 0 is an int (except when used
as a pointer, which such added behavior is what renders any cast moot)
You're starting from a flawed premise - or rather, your exception
swallows the rule.
I can't think of any static_cast that is valid. In fact g++ pukes when
you try to static_cast but allows the reinterpret_cast through just
fine.

int main()
{
int x = 0;
int *r = reinterpret_cast<int*>(x);
int *p = static_cast<int*>(x);

return 0;
}


Yes, but the following compiles fine:

int main()
{
int *r = reinterpret_cast<int*>(0);
int *p = static_cast<int*>(0);
}

What started out this subthread was your assertion that
static_cast<T*>(0) is an invalid cast. Alf Steinbach said it was
valid. He's right. In response you said that static_cast<T*>(i) was
an invalid cast where i==0. That's true, but different from your
original assertion.

Best regards,

Tom

Apr 3 '06 #10

Thomas Tutone wrote:
What started out this subthread was your assertion that
static_cast<T*>(0) is an invalid cast.


I made so such assertion (I'm being quoted out of context), in fact I
explained why it was (go back and read my first responce, I state
clearly that that cast is valid for the same reason it is unnecissary).
What I said was that if the cast was necissary it would be an invalid
one as it would be a cast from an int to a T* and that is not a valid
static cast - such a cast would have to be a reinterpret_cast.

Apr 4 '06 #11

Noah Roberts wrote:
Thomas Tutone wrote:
What started out this subthread was your assertion that
static_cast<T*>(0) is an invalid cast.
I made so such assertion (I'm being quoted out of context), in fact I
explained why it was (go back and read my first responce, I state
clearly that that cast is valid for the same reason it is unnecissary).


If you say so. I went back and read your first response. I don't see
where you say that the cast is valid, only where you say it is invalid.
But I don't want to argue semantics with you. You and I can agree
that it should not be necessary to cast 0 to assign it to a variable of
any pointer type.
What I said was that if the cast was necissary it would be an invalid
one as it would be a cast from an int to a T* and that is not a valid
static cast - such a cast would have to be a reinterpret_cast.


Best regards,

Tom

Apr 4 '06 #12
Noah Roberts wrote:
Pe*******@gmail.com wrote:

template <class T>
class Nil {
public:
operator T* () { return static_cast<T*>(0); }
That cast is invalid and, luckily, unnecissary.


Later in the thread you attempt to deny that you wrote
this statement....

The above cast is definitely valid.
You can't static_cast between unrelated types. An int and a T* are
totally unrelated.
You can static_cast in any situation where there is an implicit
conversion from source to destination.

Here's another example:

struct A { };
struct B { operator A() { return A(); } };

int main() { static_cast<A>(b); }

Classes A and B are unrelated but the static_cast is good.
Luckily enough, 0 is magic in that it can be any
pointer as well as an integral.
0 cannot be a pointer. 0 is an integer.
So, that is just calling a static cast from T* to T*
It is a static cast from the integer constant 0 to a pointer to T.

There is an implicit conversion defined from integral constants
of value 0 (also known as null-pointer constants), to pointers.
...if it wasn't the code would not compile.
Nonsense, the code is fine.
What the original coder probably intended was a reinterpret cast.
He certainly did not intend that, as a reinterpret cast would not
generate a null pointer in the case where null pointers are not
all-bits-zero. I hate to think what it would do in the case where
the pointer has more bits than an integer.
However, since the static cast worked it shows that it is not
necissary to perform any casting at all.


You just said that the code would not compile without the
static cast, now you say that the cast is not necessary.

Apr 4 '06 #13
AARRRRRRRGHHHHH!

Apr 4 '06 #14

Old Wolf wrote:
You just said that the code would not compile without the
static cast, now you say that the cast is not necessary.


Now you are just making things up.

Don't go away mad, just go away.

Apr 4 '06 #15

Diego Martins wrote:
AARRRRRRRGHHHHH!


No shit, what a bunch of wankers.

Apr 4 '06 #16
Diego Martins wrote:
AARRRRRRRGHHHHH!


When you reply using Google Groups, please hit Reply -> Preview -> Edit, to
force Google to select the replied-to text. (They are optimizing their own
servers when they trick you into leaving out that text.

Then we will know who had this wonderful affect on you.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Apr 4 '06 #17

Phlip wrote:
Diego Martins wrote:
AARRRRRRRGHHHHH!


When you reply using Google Groups, please hit Reply -> Preview -> Edit, to
force Google to select the replied-to text. (They are optimizing their own
servers when they trick you into leaving out that text.

Then we will know who had this wonderful affect on you.


heh! it was the whole thread! you are discussing the sex of the angels
:-)

Apr 4 '06 #18

Diego Martins wrote:
Phlip wrote:
Diego Martins wrote:
AARRRRRRRGHHHHH!


When you reply using Google Groups, please hit Reply -> Preview -> Edit, to
force Google to select the replied-to text. (They are optimizing their own
servers when they trick you into leaving out that text.

Then we will know who had this wonderful affect on you.


heh! it was the whole thread! you are discussing the sex of the angels
:-)


Well, I guess it is possible that Michael is a mistranslation and
should be Michelle and I _have_ met women named Gabrielle...but I'm
still under the impression that they are masculine entities.

Apr 4 '06 #19
Phlip wrote:
Diego Martins wrote:
AARRRRRRRGHHHHH!


When you reply using Google Groups, please hit Reply -> Preview ->
Edit, to force Google to select the replied-to text. (They are
optimizing their own servers when they trick you into leaving out
that text.


The method in my .sig is one step shorter.

Brian
--
Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header.
Apr 4 '06 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Jiong Feng | last post by:
Hi, Here is my problem: I created a try.htm on my server, which contains a link to the default.aspx page. if I use http://localhost/try.htm, and click the link, then in default.aspx, I could...
8
by: Pesso | last post by:
I'm having a difficulty compairing null to a class object whose "equal" operator is overridden.. Consider the following: class Foo { // ... public static bool operator==(Foo f1, Foo f2) {...
51
by: Joe Van Dyk | last post by:
When you delete a pointer, you should set it to NULL, right? Joe
4
by: Richard Coltrane | last post by:
Hi there, Im stepping into C# from VB.net. In all the examples ive seen about raising events the following construct is used: if (myevent != null) myevent(this,args); Whats the purpose of...
4
by: Debbiedo | last post by:
I searched the groups and tried several approaches but still cannot find a solution. I have a table that has several hundred fields that may or may not need to be displayed in a report,...
2
by: shankwheat | last post by:
I'm having trouble adding two values together when one of them has a null value // These two values come from a database CEOBonusValue = 550000 CEONonEqIncentCompHidden == null This should...
3
by: cmartin1986 | last post by:
I have written a sql query and I need it to return 0 when it doesn't find any matches to my criteria. I have tried adding iif statements, tried sum, and just Count, all of these methods work fine to...
2
by: Joe | last post by:
I'm binding to a column in a TemplateField. In some cases the join I have returns a null for an int field. I would like to specify a default value somehow so I don't end up with a null exception. ...
9
by: Francois Grieu | last post by:
When running the following code under MinGW, I get realloc(p,0) returned NULL Is that a non-conformance? TIA, Francois Grieu #include <stdio.h> #include <stdlib.h>
4
by: Heikki Toivonen | last post by:
I was debugging M2Crypto function written in C which changed behavior between Python 2.6 and earlier Python versions. In an error condition the function was supposed to raise exception type A, but...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.