473,769 Members | 5,885 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 25770
Tim

"Dmitry D" <wo****@telus.n et> wrote in message
news:xv******** *************@n ews0.telusplane t.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******** *************@n ews0.telusplane t.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*******@mari ani.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.l earn.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******@hotma il.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 misunderstandin gs 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.l earn.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.RE MOVE.co.uk> wrote in message news:<Xn******* *************** ************@19 5.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

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

Similar topics

3
5126
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 variable which be definied in Python. That how can I do? I have gotten the JPython 's sample that the following code can be looked. Have anyone help me to obtain same results that be called by Python's C API? What do I mean?
7
1601
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 NULL to a function, I should write like this
17
2150
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 before the first period is backwards;
9
2360
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 quote with two single quotes. Sometimes, I used SqlParameter. Maybe, I'm a bit lazy when I build the SQL string. Should I always use SqlParameters? What are the advantages/disadvantages between building SQL string and using SqlParameter? Does...
7
3464
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 DRow.Item(strCol) End If End Function
4
1854
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 it has now, after 15k lines of code resulted in a royal mess! It's my hope to ask some specific questions with scenario examples and that some of you might offer a little guidance or general suggestions. 1) string...
2
2912
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 can only make a code that work with function. Number.cpp #include "Number.h"
9
2846
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 * nPtr; //the next node's pointer }
17
2617
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 which shows harmfullness of GOTO. SoftEast...
0
9423
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10211
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9994
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9863
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8872
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6673
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5299
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3959
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.