Search code examples
pointersc89ansi-c

How shall pre ANSI-C "0 pointers" be written in ANSI C?


I am reading some old code and I am finding structures like this one:

Symbol *lookup(s)
    char *s;
{
    Symbol *sp;
    for(sp=symlist; sp!= (Symbol *)0; sp = sp->next)
        if(strcmp(sp->name, s) == 0)
            return sp;
    return 0;
}

I understand that the arguments can be specified in ANSI C in the following way:

Symbol *lookup(char *s) {
   ...
}

But I am wondering what to do with the 0 pointers:

(Symbol *) 0

Solution

  • sp != (Symbol *)0 is still perfectly valid in ANSI/ISO C. Any integer constant expression with the value 0 can be used as null pointer constant (C17 6.3.2.3 (3)), and can be cast to any pointer type, resulting in a null pointer of that type. So this simply repeats the loop as long as sp is not a null pointer.

    It might be a little more conventional to rewrite it as sp != NULL, but it's not necessary. If you prefer to be terse, you can also simply write

    for(sp=symlist; sp; sp = sp->next)