473,320 Members | 2,147 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,320 software developers and data experts.

A question about NULL

Hi,
I'm new to C++ (started learning in the beginning of this summer), and I
have the following question (sorry if it sounds stupid):
In many code samples and source files, I see NULL expression being used (for
example, int* someInt=NULL; ). I used similar initialization myself, and it
works fine even if I don't define NULL. But what is "NULL" exactly? Is it a
constant defined by compiler? Is there any difference between the following
two ways to initialize a pointer?
// example 1
int * myInt = NULL;

// example 2
int * myInt = 0;

If there is no difference, why would I use NULL instead of 0?
Thanks in advance.

Dmitry
P.S. This is my first post in the newsgroup :)
Jul 19 '05 #1
11 25712
Tim

"Dmitry D" <wo****@telus.net> wrote in message
news:xv*********************@news0.telusplanet.net ...
Hi,
I'm new to C++ (started learning in the beginning of this summer), and I
have the following question (sorry if it sounds stupid):
In many code samples and source files, I see NULL expression being used (for example, int* someInt=NULL; ). I used similar initialization myself, and it works fine even if I don't define NULL. But what is "NULL" exactly? Is it a constant defined by compiler? Is there any difference between the following two ways to initialize a pointer?
// example 1
int * myInt = NULL;

// example 2
int * myInt = 0;


In 'C', NULL is defined like this:

#define NULL (void*)0
In C++, NULL is defined like this:

#define NULL 0
If you try and initialise a pointer to a type with a pointer to void, you'll
get errors with a C++ compiler:

int* p = (void*)0; // OK in 'C*, error in C++
int* p = 0; // OK in C++, error in 'C'
C++ specifically forbids the 'C' style definition of NULL. Why? Perhaps
assigning a 'pointer to a type' to the 'C' style NULL could be considered
similar to assigning a 'pointer to a derived type' to a 'pointer to base
type', which would be wrong. Then again, is assigning a 'pointer to a type'
to the value zero is any more correct; besides which 'void' is not the base
type of all types? You could say that it's a bit of shambles (I do). Then
again, C++ isn't a real OO language; it's a baggage of OO extensions to 'C'
which is, essentially, just portable assembler. To do the job properly, you
would need a language that had a common base type for all types and Null
instances of every derived type.
Jul 19 '05 #2
Dmitry D wrote:
Hi,
I'm new to C++ (started learning in the beginning of this summer), and I
have the following question (sorry if it sounds stupid):
In many code samples and source files, I see NULL expression being used (for
example, int* someInt=NULL; ). I used similar initialization myself, and it
works fine even if I don't define NULL. But what is "NULL" exactly? Is it a
constant defined by compiler? Is there any difference between the following
two ways to initialize a pointer?
// example 1
int * myInt = NULL;

// example 2
int * myInt = 0;

If there is no difference, why would I use NULL instead of 0?
Thanks in advance.

Dmitry
P.S. This is my first post in the newsgroup :)


NULL is usually a macro

#define NULL 0

and sometimes (but only for C as C++

#define NULL ((void *) 0)
'0' is a special case in the sense that

int * ptr = 0; // happy compiler

Is perfectly legal ... but

int * ptr = 1; // Illegal - cranky compiler

error: invalid conversion from `int' to `int*'
Why NULL? Some would argue readability. Some would argue that NULL is
not neccassarily '0', for example I *could* (but I would never) define
NULL and ((void *) 1).

NULL is usually defined in one of the standard header files.
Jul 19 '05 #3
Dmitry D wrote in news:xv*********************@news0.telusplanet.net :
Hi,
I'm new to C++ (started learning in the beginning of this summer), and
I have the following question (sorry if it sounds stupid):
In many code samples and source files, I see NULL expression being
used (for example, int* someInt=NULL; ). I used similar initialization
myself, and it works fine even if I don't define NULL. But what is
"NULL" exactly? Is it a constant defined by compiler? Is there any
difference between the following two ways to initialize a pointer?
// example 1
int * myInt = NULL;

// example 2
int * myInt = 0;

If there is no difference, why would I use NULL instead of 0?
Thanks in advance.


NULL is a #define's macro to use it you have to include one of
the system header's that defines it, but don't use it.

In C++ NULL is usually defined to be 0 or 0L, so there is no
difference in the 2 examples you gave.

In C NULL is usually defined to be ((void *)0), this is more
"typesafe" in C.

So the macro NULL is useful if you have some code that is going to
bee seen by a C compiler and a C++ compiler, otherwise use 0 for C++.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 19 '05 #4
Tim

"Rolf Magnus" <ra******@t-online.de> wrote in message
news:bh*************@news.t-online.com...
Rob Williscroft wrote:
Hi,
I'm new to C++ (started learning in the beginning of this summer),
and I have the following question (sorry if it sounds stupid):
In many code samples and source files, I see NULL expression being
used (for example, int* someInt=NULL; ). I used similar
initialization myself, and it works fine even if I don't define NULL.
But what is "NULL" exactly? Is it a constant defined by compiler? Is
there any difference between the following two ways to initialize a
pointer? // example 1
int * myInt = NULL;

// example 2
int * myInt = 0;

If there is no difference, why would I use NULL instead of 0?
Thanks in advance.


NULL is a #define's macro to use it you have to include one of
the system header's that defines it, but don't use it.

In C++ NULL is usually defined to be 0 or 0L, so there is no
difference in the 2 examples you gave.

In C NULL is usually defined to be ((void *)0), this is more
"typesafe" in C.


Actually, it's not. It just fools the user into thinking that it's more
typesafe.


Is that true? Surely it 'really' is safer to initialise a pointer to type
with a ((void*)0); for instance, what about x86 segmented architecture;
there 0 and (void*(0)) really are quite different animals (only the offset
part of the pointer is zero).
So the macro NULL is useful if you have some code that is going to
bee seen by a C compiler and a C++ compiler, otherwise use 0 for C++.


There is no reason to use NULL in C either.


....but it makes the intention clear, namely that you're at least
initialising a pointer to type with a pointer, not an integer.
Jul 19 '05 #5
On 16 Aug 2003 08:17:09 GMT, Gianni Mariani <gi*******@mariani.ws>
wrote in comp.lang.c++:
Dmitry D wrote:
Hi,
I'm new to C++ (started learning in the beginning of this summer), and I
have the following question (sorry if it sounds stupid):
In many code samples and source files, I see NULL expression being used (for
example, int* someInt=NULL; ). I used similar initialization myself, and it
works fine even if I don't define NULL. But what is "NULL" exactly? Is it a
constant defined by compiler? Is there any difference between the following
two ways to initialize a pointer?
// example 1
int * myInt = NULL;

// example 2
int * myInt = 0;

If there is no difference, why would I use NULL instead of 0?
Thanks in advance.

Dmitry
P.S. This is my first post in the newsgroup :)
NULL is usually a macro


Actually the C and C++ standards both require that NULL is a macro.
#define NULL 0

and sometimes (but only for C as C++

#define NULL ((void *) 0)
'0' is a special case in the sense that

int * ptr = 0; // happy compiler

Is perfectly legal ... but

int * ptr = 1; // Illegal - cranky compiler

error: invalid conversion from `int' to `int*'
Why NULL? Some would argue readability. Some would argue that NULL is
not neccassarily '0', for example I *could* (but I would never) define
NULL and ((void *) 1).
NULL, at least in C++, is necessarily 0, although it may not be the
literal character constant '0'. The C++ language standard requires
that the macro NULL expand to an integer constant expression that
evaluates to 0.

So it could be:

#define NULL (42-4*7)

....but it can't be defined as ((void *)1). In fact it can't be
defined as a pointer at all in C++. It can in C, but only (again) as
an integer constant expression that evaluates to 0 being cast to a
pointer to void.
NULL is usually defined in one of the standard header files.


NULL is required to be defined in several of the standard header
files.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
Jul 19 '05 #6
On Sat, 16 Aug 2003 20:46:52 +0200, "Tim" <ti******@hotmail.com> wrote
in comp.lang.c++:

"Rolf Magnus" <ra******@t-online.de> wrote in message
news:bh*************@news.t-online.com...
Rob Williscroft wrote:
> Hi,
> I'm new to C++ (started learning in the beginning of this summer),
> and I have the following question (sorry if it sounds stupid):
> In many code samples and source files, I see NULL expression being
> used (for example, int* someInt=NULL; ). I used similar
> initialization myself, and it works fine even if I don't define NULL.
> But what is "NULL" exactly? Is it a constant defined by compiler? Is
> there any difference between the following two ways to initialize a
> pointer? // example 1
> int * myInt = NULL;
>
> // example 2
> int * myInt = 0;
>
> If there is no difference, why would I use NULL instead of 0?
> Thanks in advance.
>

NULL is a #define's macro to use it you have to include one of
the system header's that defines it, but don't use it.

In C++ NULL is usually defined to be 0 or 0L, so there is no
difference in the 2 examples you gave.

In C NULL is usually defined to be ((void *)0), this is more
"typesafe" in C.
Actually, it's not. It just fools the user into thinking that it's more
typesafe.


Is that true? Surely it 'really' is safer to initialise a pointer to type
with a ((void*)0); for instance, what about x86 segmented architecture;
there 0 and (void*(0)) really are quite different animals (only the offset
part of the pointer is zero).


You have some misunderstandings here. First, C++ disallowed the C
definition of NULL as (void *)0 because it runs afoul of the typing
system. The following is legal C but illegal C++:

char *cp = (void *)0;

C allows conversion to and from void pointer to any object type
without a cast, C++ only allows the conversion from pointer to object
to void pointer, not the other way.

Second, perhaps you misunderstand something else. An integer constant
expression that evaluates to 0 is "magic" in C and C++ when used in a
pointer context. It makes no difference what the size of a pointer
is, or whether the architecture is segmented or has other unusual
quirks.

The expression:

type *type_pointer = 0;

....sets the pointer to a null pointer. That does not mean that a null
pointer has all bits 0 in its physical representation.

The compiler must recognize the use of such an expression at compile
time, and convert it to whatever the implementation uses internally as
an actual null pointer value.

Note that this only applies to compile time constant expressions. The
following:

int x = 0;
char *cp;
cp = x;

....is not guaranteed to make cp a null pointer.

Compilers have been required to perform this recognition and special
handling for constant 0 in a pointer context for at least 30 years
now, long before K&R1, long before the first ANSI C standard, and long
before Bjarne started extending C into C++.
So the macro NULL is useful if you have some code that is going to
bee seen by a C compiler and a C++ compiler, otherwise use 0 for C++.


There is no reason to use NULL in C either.


...but it makes the intention clear, namely that you're at least
initialising a pointer to type with a pointer, not an integer.


This is the most important point. The three most common expressions
for 0 in C++ are 0, '\0', and NULL.

You could write:

char *cp = '\0'; // '\0' is a perfectly valid null pointer constant!

You could also write:

char ca [100];
ca [99] = NULL;

....but you wouldn't last long working on any project I was running!

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
Jul 19 '05 #7
Tim wrote:

In 'C', NULL is defined like this:

#define NULL (void*)0
In C++, NULL is defined like this:

#define NULL 0


NULL *may* be defined that way in C. It may also look like your second
example. Both are acceptable in C, but only the second is acceptable in
C++. However, it's not the *only* thing that's acceptable in C++. These
are also legal definitions of NULL in C++:

#define NULL 0L
#define NULL (1 - 1)
#define NULL !1
#define NULL !!0
#define NULL !!!!!!!!!!!!!!!!!!!!!!!!!!!1

In C, I use NULL to make it more obvious that I'm dealing with pointers.
In C++ that can be a dangerous way of thinking, because NULL is *not*,
in fact, a pointer. So if you have an overloaded function:

void f(long i);
void f(void *p);

And you attempt to call f(void *) this way:

f(NULL);

You will call the wrong function. NULL can lead you to believe you are
using a pointer when, if fact, you are not.

Technically, NULL can also be changed in a program:

#undef NULL
#define NULL 27

Which could cause serious problems. This is another reason to avoid it
and use 0 instead, but I think this one is a bit of a stretch. I can't
imagine why someone would do something like that.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #8
Jack Klein wrote:
[snip]


NULL, at least in C++, is necessarily 0, although it may not be the
literal character constant '0'. The C++ language standard requires
that the macro NULL expand to an integer constant expression that
evaluates to 0.

So it could be:

#define NULL (42-4*7)


OK Jack. It's Saturday. Step away from the keyboard. Easy now...

;-)

--ag
--
Artie Gold -- Austin, Texas

Jul 19 '05 #9
Rob Williscroft <rt*@freenet.REMOVE.co.uk> wrote in message news:<Xn**********************************@195.129 .110.200>...
NULL is a #define's macro to use it you have to include one of
the system header's that defines it, but don't use it.

In C++ NULL is usually defined to be 0 or 0L, so there is no
difference in the 2 examples you gave.

In C NULL is usually defined to be ((void *)0), this is more
"typesafe" in C.

So the macro NULL is useful if you have some code that is going to
bee seen by a C compiler and a C++ compiler, otherwise use 0 for C++.


Your conclusion doesn't follow. How is it "useful" to have the
definition of NULL change? All it can do is introduce bugs.

For example:

printf("%p", NULL);

is legal if NULL=(void*)0, but a bug if NULL=0.

Sam
Jul 19 '05 #10
Jack Klein <ja*******@spamcop.net> wrote in message news:<s9********************************@4ax.com>. ..
Compilers have been required to perform this recognition and special
handling for constant 0 in a pointer context for at least 30 years
now, long before K&R1, long before the first ANSI C standard, and long
before Bjarne started extending C into C++.


I don't think that's historically accurate. In the very early C days,
it was permitted to mix integers and pointers (without casts), so 0
wasn't treated differently than any other integer.

From http://cm.bell-labs.com/cm/cs/who/dmr/chist.html

"The language changes during this period, especially around 1977, were
largely focused on considerations of portability and type safety, in
an effort to cope with the problems we foresaw and observed in moving
a considerable body of code to the new Interdata platform. C at that
time still manifested strong signs of its typeless origins. Pointers,
for example, were barely distinguished from integral memory indices in
early language manuals or extant code; the similarity of the
arithmetic properties of character pointers and unsigned integers made
it hard to resist the temptation to identify them. The unsigned types
were added to make unsigned arithmetic available without confusing it
with pointer manipulation. Similarly, the early language condoned
assignments between integers and pointers, but this practice began to
be discouraged; a notation for type conversions (called `casts' from
the example of Algol 68) was invented to specify type conversions more
explicitly. ..."

"Compilers in 1977, and even well after, did not complain about usages
such as assigning between integers and pointers or using objects of
the wrong type to refer to structure members. Although the language
definition presented in the first edition of K&R was reasonably
(though not completely) coherent in its treatment of type rules, that
book admitted that existing compilers didn't enforce them."

Sam
Jul 19 '05 #11
Tim

"Jack Klein" <ja*******@spamcop.net> wrote in message
news:s9********************************@4ax.com...
On Sat, 16 Aug 2003 20:46:52 +0200, "Tim" <ti******@hotmail.com> wrote
in comp.lang.c++:

"Rolf Magnus" <ra******@t-online.de> wrote in message
news:bh*************@news.t-online.com...
Rob Williscroft wrote:

>> Hi,
>> I'm new to C++ (started learning in the beginning of this summer),
>> and I have the following question (sorry if it sounds stupid):
>> In many code samples and source files, I see NULL expression being
>> used (for example, int* someInt=NULL; ). I used similar
>> initialization myself, and it works fine even if I don't define NULL. >> But what is "NULL" exactly? Is it a constant defined by compiler? Is >> there any difference between the following two ways to initialize a
>> pointer? // example 1
>> int * myInt = NULL;
>>
>> // example 2
>> int * myInt = 0;
>>
>> If there is no difference, why would I use NULL instead of 0?
>> Thanks in advance.
>>
>
> NULL is a #define's macro to use it you have to include one of
> the system header's that defines it, but don't use it.
>
> In C++ NULL is usually defined to be 0 or 0L, so there is no
> difference in the 2 examples you gave.
>
> In C NULL is usually defined to be ((void *)0), this is more
> "typesafe" in C.

Actually, it's not. It just fools the user into thinking that it's more typesafe.
Is that true? Surely it 'really' is safer to initialise a pointer to type with a ((void*)0); for instance, what about x86 segmented architecture;
there 0 and (void*(0)) really are quite different animals (only the offset part of the pointer is zero).


You have some misunderstandings here. First, C++ disallowed the C
definition of NULL as (void *)0 because it runs afoul of the typing
system. The following is legal C but illegal C++:

char *cp = (void *)0;

C allows conversion to and from void pointer to any object type
without a cast, C++ only allows the conversion from pointer to object
to void pointer, not the other way.


Why would you think I have a misunderstanding here; all you've done is
repeat what I said in an earlier reply in this thread?
Second, perhaps you misunderstand something else. An integer constant
....that would be in addition to the first thing that I actually understood,
would it?
expression that evaluates to 0 is "magic" in C and C++ when used in a
pointer context. It makes no difference what the size of a pointer
is, or whether the architecture is segmented or has other unusual
quirks.

The expression:

type *type_pointer = 0;

...sets the pointer to a null pointer. That does not mean that a null
pointer has all bits 0 in its physical representation.

The compiler must recognize the use of such an expression at compile
time, and convert it to whatever the implementation uses internally as
an actual null pointer value.

Note that this only applies to compile time constant expressions. The
following:

int x = 0;
char *cp;
cp = x;

...is not guaranteed to make cp a null pointer.

Compilers have been required to perform this recognition and special
handling for constant 0 in a pointer context for at least 30 years
now, long before K&R1, long before the first ANSI C standard, and long
before Bjarne started extending C into C++.


I could be wrong (it was a long time a go) but going back to the days of
Microsoft C 5 (about 15 years a go?), I think you'll find that you would
have had problems if you initialised pointers to 0 (instead of ((void
far*)0) or ((void near*)0) or ((void huge*)0).
> So the macro NULL is useful if you have some code that is going to
> bee seen by a C compiler and a C++ compiler, otherwise use 0 for C++.
There is no reason to use NULL in C either.


...but it makes the intention clear, namely that you're at least
initialising a pointer to type with a pointer, not an integer.


This is the most important point. The three most common expressions
for 0 in C++ are 0, '\0', and NULL.

You could write:

char *cp = '\0'; // '\0' is a perfectly valid null pointer constant!

You could also write:

char ca [100];
ca [99] = NULL;

...but you wouldn't last long working on any project I was running!

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq

Jul 19 '05 #12

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

Similar topics

3
by: Link | last post by:
Dear sir, I am used to developing C program on MSVC7.0 platform. This is my first time to use Python for calling by C program. Now, it is hard to deal with the problem about extracting the...
7
by: I wish | last post by:
http://www.eskimo.com/~scs/C-faq/q5.4.html It says "In particular, a cast may still be necessary before NULL (as before 0) in a function call argument." Does that mean if I want to pass a...
17
by: kj | last post by:
How can one test if a pointer has been "freed" (i.e. with free())? My naive assumption was that such a pointer would equal NULL, but not so. Thanks, kj -- NOTE: In my address everything...
9
by: Michael | last post by:
Hi all, I would like to get people's opinion about executing SQL statements in C# (or any other .NET language really). I used to create my SQL statement by building a string and replacing single...
7
by: Adrian Parker | last post by:
'function to convert null to nothing Function CheckDate(ByVal DRow As DataRow, ByVal strCol As String) As Date If DRow.Item(strCol) Is System.DBNull.Value Then Return Nothing Else Return...
4
by: Steve | last post by:
I have read a couple articles online, read my Jesse Liberty book but I am still confused as to just what the best practices are for using exceptions. I keep changing how I'm working with them and...
2
by: TheRomance | last post by:
i have a problem about insert integer to link list. sorry it's too long but i try many times, many ways , it's still have an error function is fix . can't change anything about function. i...
9
by: william | last post by:
When implementing Linked list, stack, or trees, we always use pointers to 'link' the nodes. And every node is always defined as: struct node { type data; //data this node contains ... node *...
17
by: SoftEast | last post by:
Hi Buddies, I have read a lot of stuffs regarding not using GOTO statements to opt a good programming style http://david.tribble.com/text/goto.html]. Can anybody give a particular lines of code...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.