Casting NULL to a struct pointer in C?
Asked Answered
S

4

8

Is there any benefit of casting NULL to a struct pointer in C ?

For example:

typedef struct List
{
....
} List;

List *listPtr = ((List *) NULL) ;

Example from PostgreSQL source:

#define NIL                     ((List *) NULL)

http://doxygen.postgresql.org/pg__list_8h_source.html

Swayne answered 23/8, 2012 at 14:39 Comment(1)
This doesn't make any sense to me. You can assign NULL to any pointer without any cast.Hogarth
B
10

In assignment example the explicit cast make no useful sense. However, it seems that you the question is really about #define NIL ((List *) NULL) macro, whose usability extends beyond assignment.

One place where it might make sense is when you pass it to a variadic function or to a function declared without a prototype. The standard NULL can be defined as0 or 0L or ((void *) 0) or in some other way, meaning that it might be interpreted differently in such type-less contexts. An explicit cast will make sure that it is interpreted correctly as a pointer.

For example, this is generally invalid (behavior is undefined)

void foo();

int main() {
  foo(NULL);
}

void foo(List *p) {
  /* whatever */
}

while replacing the call with

foo(NIL);

makes it valid.

Banerjee answered 23/8, 2012 at 14:47 Comment(0)
T
6

No null is null, it's as null as you can get, you might think zero is pretty null but that's just peanuts compared to null.

Tavis answered 23/8, 2012 at 14:41 Comment(3)
Still some HHGTTG fans in this new generation then ;-)Tavis
oh, no, unfortunately not. sizeof(NULL) can vary from 1 to 8 depending on how NULL is defined.Grizzle
@JensGustedt that's just the representation of NULL in our universe.Tavis
S
4

Is there any benefit of casting NULL to a struct pointer in C

There's none. It should be simply:

List *listPtr = NULL;

Moreover, if the object has static storage (say, like a global variable) you don't even need to initialize it to NULL.

Swen answered 23/8, 2012 at 14:41 Comment(0)
T
0

Yes, there is benefit. In this example, you can use size_of_attribute() macro to determine a size in bytes of a specific struct attribute, without actually creating an instance of said struct.

#define size_of_attribute(Struct, Attribute) sizeof(((Struct*)NULL)->Attribute)
Tobacconist answered 5/5, 2023 at 11:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.