Hacker News new | ask | show | jobs
by timq 2497 days ago
A little off-topic but here is a cool piece of code about a special case in C:

    void (*foo)() = 0;
    void (*bar)() = (void *)0;
    void (*baz)() = (void *)(void *)0; // Error
Can you guess why compilers reject the last line?
2 comments

Only the first two expressions on the right are null pointer constants (integral constant expression with a value of 0, optionally cast as a void *), that can be used to initialize all pointer variables, including function pointers. The last one is merely a null pointer (to void), that can't be implicitly converted to a pointer to a function.

C++ has stricter rules for null pointer constants, and thus only the first version is valid C++.

Most modern compilers don't even warn about the last line unless you're in pedantic mode.