M.E.
M.E.

Reputation: 5505

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

Upvotes: 0

Views: 47

Answers (2)

Nate Eldredge
Nate Eldredge

Reputation: 58593

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)

Upvotes: 1

LeleDumbo
LeleDumbo

Reputation: 9340

That's just a way to specify typed null pointer, instead of the more common NULL from stdlib.h which has void* type, no way at all related with the way parameters specified in K&R C.

Upvotes: 1

Related Questions