-5
#include <stdio.h>
#include <iostream>
int main() 
{
  if(NULL)
    std::cout<<"hello";
  else
    std::cout<<"world";
  return 0;
}

The output to the above question is:

world

Kindly explain me why am I getting this output. I am not able to get the satisfactory answer even after referring to several different sources.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Palak Jain
  • 17
  • 6
  • 4
    NULL == 0 == false (for a given definition of ==). Therefore the if statement becomes `if(false)` etc – Richard Critten Aug 20 '17 at 13:36
  • I am learning C++, and I read somewhere that NULL and 0 are different. So, I am a bit confused. – Palak Jain Aug 20 '17 at 13:37
  • Have a read of: http://en.cppreference.com/w/cpp/types/NULL – Richard Critten Aug 20 '17 at 13:38
  • [What is the difference between NULL, '\0' and 0](https://stackoverflow.com/questions/1296843/what-is-the-difference-between-null-0-and-0) – user7860670 Aug 20 '17 at 13:39
  • 1
    *I read somewhere that NULL and 0 are different*. Don't read anything from that place. The language requires NULL and 0 to be identical. – n. m. could be an AI Aug 20 '17 at 13:39
  • I can't imagine any language where NULL is a "truthy" value. – David Aug 20 '17 at 13:41
  • 1
    *I read somewhere that NULL and 0 are different.* - Conceptually, they are different. That is, you should not, for example, use `NULL` for numeric computations. But technically, when evaluated in a context where it is interpreted as a number `NULL` will always yield the value `0` (at least before C++11). – ComicSansMS Aug 20 '17 at 13:41
  • gotcha! @ComicSansMS – Palak Jain Aug 20 '17 at 13:49
  • @PalakJain you might have confused `NULL` and `nullptr`. `nullptr` is the one that has a separate type, but even that will be implicitly converted to a type that will evaluate to false. – PeterT Aug 20 '17 at 14:01

1 Answers1

1

NULL results in a false condition. You could imagine that NULL is a 0, so this:

if(NULL)

would be equivalent to this:

if(0)

thus your code would become:

#include <stdio.h>
#include <iostream>
int main() 
{
  if(0)
    std::cout<<"hello";
  else
    std::cout<<"world";
  return 0;
}

where is obvious that because 0 results to false, the if condition is not satisfied, thus the body of the if-statement is not executed. As a result, the body of the else-statement is executed, which explains the output you see.


PS: Correct way of defining NULL and NULL_POINTER?

gsamaras
  • 71,951
  • 46
  • 188
  • 305