Click here to Skip to main content
15,907,326 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The following code outputs 4:

C++
#include<stdio.h>
int main()
{

    printf("%d",1+(int)NULL);
}


While the following code outputs1:
C++
#include
int main()
{

    printf("%d",1+(int)NULL);
}


What I have tried:

I don't understand why the above codes differ differ?
Posted
Updated 12-Mar-16 5:14am
v3
Comments
CHill60 12-Mar-16 10:53am    
What was the #include in the second program and are you sure that you have posted both programs here correctly?
Are these running on the same machine / operating system?

1 solution

Probably because stdio.h #defines NULL to a specific value if it isn't defined.
The standard VS C++ stdio.h uses this:
C++
/* Define NULL pointer value */
#ifndef NULL
#ifdef __cplusplus
#define NULL    0
#else  /* __cplusplus */
#define NULL    ((void *)0)
#endif  /* __cplusplus */
#endif  /* NULL */
But it would be possible to define a NULL that still ended up as a void pointer after the addition of the (int) cast. And since a pointer + 1 increments by the size of a "machine word", it's quite likely that in a 32 bit environment, the resulting address would be four.
I'd start by looking at the exact content of your include files and check what they define NULL as (since it isn't defined as a C or C++ keyword)
 
Share this answer
 
Comments
Member 12378355we 12-Mar-16 12:32pm    
Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900