3

I know that a NULL pointer is (void*)0.But what happens when we use statements like the following:

  if(ptr==NULL)

where ptr can be a char,float or int pointer?Is NULL guaranteed to be implicitly converted to the type on the left just as, for example, in C, the type returned by malloc() is void* but is implicitly converted to the type of the lvalue?

Thokchom
  • 1,602
  • 3
  • 17
  • 32

3 Answers3

6

Is NULL guaranteed to be implicitly converted to the type on the left? [...]

Yes.

According to section 6.3.2.3.4 of the ISO/IEC 9899:2011 C programming language standard:

Conversion of a null pointer to another pointer type yields a null pointer of that type. Any two null pointers shall compare equal.

and to section 6.3.2.3.1

A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

Alex Bitek
  • 6,529
  • 5
  • 47
  • 77
2

I know that a NULL pointer is (void*)0

Not necessarily. The macro NULL could be defined as 0, (void*)0 or something else. The only requirement is that it is compatible with a null pointer for the specific implementation. In theory, a compiler could define NULL as 1, but in practice nobody does that.

Is NULL guaranteed to be implicitly converted to the type on the left

Yes, any expression where a null pointer is used together with another kind of pointer yields a null pointer. This has nothing to do with some implementations defining NULL as (void*). The C standard simply guarantees null pointer conversions, no matter the NULL macro.

in C, the type returned by malloc() is void* but is implicitly converted to the type of the lvalue?

Yes, in C a void* will always be implicitly converted to/from a pointer of another type (in C++, you would however need an explicit cast).

Lundin
  • 195,001
  • 40
  • 254
  • 396
0

The magic happens because of the (void*) part. A void pointer can point to anything. So comparing any pointer to NULL is quite okay.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    the C standard establish that `void *` must be compatible with any other pointer type, and if your compiler follow the standard, you should never be worried about make assignments and comparisons using void pointers. – Jonatan Goebel May 15 '13 at 11:16
  • 1
    NULL isn't necessarily (void*)0, so to be picky and formal, this answer isn't correct. – Lundin May 15 '13 at 11:34
  • @Lundin You are correct, but on the other hand it must be compatible with all pointer types, which basically means it _has_ to be a `void*`. – Some programmer dude May 15 '13 at 11:45