8

I have this piece of code in C:

void f(void *x) {
    printf(">>> %p\n", x);
}

int main() {

  f NULL;
    return 0;
}

I think is for the definition of NULL, but I'd like an explanation to clarify my doubt.

Kyrol
  • 3,475
  • 7
  • 34
  • 46

2 Answers2

9

If NULL is defined as ((void *)0) or (0), then this expands to f ((void *)0) or f (0), which are proper function calls. The code errors out for anything non-parenthesized during compilation.

2

In C NULL is often defined as follows:

#if !defined(NULL)
    #define NULL ((void*)0)
#endif

If this is the case then NULL is just a special pointer, and you example works.

jbr
  • 6,198
  • 3
  • 30
  • 42
  • No, the C standard doesn't define how NULL should be defined. –  May 31 '13 at 08:10
  • 5
    Also, `NULL` is not a pointer *to the address 0*. Rather, the *literal value 0*, when encountered in a pointer context, is the null pointer. The *actual* value of the null pointer is implementation-specific and can be anything. – Jon May 31 '13 at 08:12
  • 2
    Fair enough, the standard says that the definition of NULL is implementation specific. However in section 6.3.2.3 part 3, in http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf. It says that a `0` cast to (void *) is called a null pointer constant. – jbr May 31 '13 at 08:17
  • 3
    @jbr: Exactly, a *literal* `0` gives a null ptr. But for example, this is not (technically) a null ptr: `int a = 0; void* p = (void*)a;`. – Jon May 31 '13 at 08:20