0

What is the difference between return NULL and return 0 in C?

Yes, I know that 0 is a number and NULL is a void. But I don't understand the purpose of the two in context of programming.

Also I believe return 0 doesn't return the number 0 to calling function, but returns void. So what difference would it make if the statements return NULL and return 0 are interchanged?

glglgl
  • 89,107
  • 13
  • 149
  • 217
  • 4
    NULL is *not* a `void`. Void has no value, it's nonexistent! – Richard J. Ross III Nov 04 '13 at 08:31
  • 4
    http://stackoverflow.com/questions/1296843/what-is-the-difference-between-null-0-and-0?rq=1 – David Sykes Nov 04 '13 at 08:31
  • 1
    void it a type. Null is a valid value for a void pointer – David Sykes Nov 04 '13 at 08:32
  • 1
    Besides the technical answer, even if there were no difference, it would still be correct to use NULL to refer to a canonical invalid pointer, and never to an integer value, and incorrect to ever do anything else. Semantic development often follows statement of intent, so it's worthwhile to say what you mean just for its own sake. – Potatoswatter Nov 04 '13 at 08:36

1 Answers1

1

In C

#define NULL  ((void*) 0)

That means NULL is of type void* (a pointer without a type). And the value for it is 0.

There is no difference in assigning zero or NULL to a pointer variable. NULL may be just more readable.

See: http://c-faq.com/null/macro.html

When you are returning zero, you are really returning zero. If a function signature has void specified as a return value, it means that the function does not return a value. In some other languages this is known as a "procedure".

David Ranieri
  • 39,972
  • 7
  • 52
  • 94
teroi
  • 1,087
  • 10
  • 19
  • Mostly, but not always, see [Question 5.17](http://c-faq.com/null/machexamp.html) of the same FAQ, see also: [When was the NULL macro not 0?](http://stackoverflow.com/q/2597142/1606345) – David Ranieri Nov 04 '13 at 09:15
  • Quite right. There are some esoteric exceptions to the rule. – teroi Nov 04 '13 at 11:46