Last active
January 2, 2017 22:07
-
-
Save kioba/ffce26ac55c3c5155d04 to your computer and use it in GitHub Desktop.
c++11 what is 0, NULL and nullptr?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
void whatis(int*& pointer); | |
int main() | |
{ | |
int* isempty; | |
int* zero = 0; | |
int* null = NULL; | |
int* nullpointer = nullptr; | |
std::cout << "isempty:" << std::endl; | |
whatis(isempty); | |
std::cout << "zero:" << std::endl; | |
whatis(zero); | |
std::cout << "null:" << std::endl; | |
whatis(null); | |
std::cout << "nullpointer:" << std::endl; | |
whatis(nullpointer); | |
std::cin.get(); | |
return 0; | |
} | |
void whatis(int*& pointer) | |
{ | |
if (pointer == 0) { | |
std::cout << "\t 0" << std::endl; | |
} | |
if (pointer == NULL) { | |
std::cout << "\t NULL" << std::endl; | |
} | |
if (pointer == nullptr) { | |
std::cout << "\t nullptr" << std::endl; | |
} | |
} |
This code snippet is not written in C11, but written in C++11. Not the same language. file should be named nullptr.c
instead of nullptr.cpp
. GCC detects that file extension difference and uses a different compiler under the hood (cc1
instead of cc1plus
). Also, you can't use <iostream>
because that doesn't exist in C. when compiling this snippet using gcc or clang, make sure you add the -std=c11
flag to enable c11. Otherwise, it would default to c99, which is the previous ansi standard. If I recall correctly, nullptr
doesn't even exist in C. You have to use NULL
, which should be a defined as ((void*)0)
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I tried this and all three of them came out to equal all three? WTF?