Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is NULL always zero in C?

I was interviewing a guy for a mid-level software engineering position yesterday, and he mentioned that in C, NULL is not always zero and that he had seen implementations of C where NULL is not zero. I find this highly suspect, but I want to be sure. Anyone know if he is right?

(Responses will not affect my judgement on this candidate, I've already submitted my decision to my manager.)

like image 310
chi42 Avatar asked Mar 27 '12 16:03

chi42


People also ask

Is null the same as 0 in C?

NULL is use as an abstraction because at the time it was not clear what the value of NULL would be from system to system. So the standard value is zero, Which is the same for '0'. Using NULL or '0' you are sure your code would work on any system regardless of what their values are. So NULL is a _global_ constant.

IS null same as 0?

No, it's not the same as null means a value that is unavailable, unassigned or unknown and zero is a defined value.

IS NULL character 0 or O?

A null character refers to any character that has a numeric value of zero. It is termed a null character as it doesn't carry a value and all its bit are set on 0.

Can we write null in C?

The Null character in the C programming language is used to terminate the character strings. In other words, the Null character is used to represent the end of the string or end of an array or other concepts in C. The end of the character string or the NULL byte is represented by '0' or '\0' or simply NULL.


2 Answers

I'm assuming you mean the null pointer. It is guaranteed to compare equal to 0.1 But it doesn't have to be represented with all-zero bits.2

See also the comp.lang.c FAQ on null pointers.


  1. See C99, 6.3.2.3.
  2. There's no explicit claim; but see the footnote for C99, 7.20.3 (thanks to @birryree in the comments).
like image 67
Oliver Charlesworth Avatar answered Sep 25 '22 20:09

Oliver Charlesworth


§ 6.3.2.3 of the C99 standard says

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

§ 7.17 also says

[...] NULL which expands to an implementation-defined null pointer constant [...]

The address of the NULL pointer might be different from 0, while it will behave like it was in most cases.

(This should be the same as in older C standards, which I don't have at hand right now)

like image 28
johannes Avatar answered Sep 25 '22 20:09

johannes