Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you return(0*ap++)?

Tags:

c

It's K&R-C and here is the whole code: http://v6shell.org/history/if.c

Look at this function:

char *nxtarg() {
    if (ap>ac) return(0*ap++);
    return(av[ap++]);
}

1.Question: Why return (0*ap++)? Okay you want to return 0 and increase ap by 1. But why like this? Is it faster than if (ap>ac) {ap++; return 0;}?

2.Question: The return type of nxtarg has to be char*, why can you return 0, an integer?

like image 312
Joey Avatar asked Jan 01 '15 19:01

Joey


2 Answers

This is a little trick to squeeze the increment into a statement that returns zero. It is logically equivalent to a conditional

if (ap > ac) {
    ap++;
    return 0;
}

or even better with a comma operator:

return (ap++, (char *)0); // Thanks, Jonathan Leffler

Note that since zero in your example is not a compile-time constant, the expression needs a cast to be compliant with the standard:

if (ap>ac) return (char*)(0*ap++);

As far as returning an integer zero goes, it is considered to be equal to NULL pointer when used in pointer context.

like image 121
Sergey Kalinichenko Avatar answered Sep 21 '22 11:09

Sergey Kalinichenko


The ++ operator will increment the value, and return the value before it was incremented. If the function was supposed to return a pointer, you can return zero or NULL, to indicate a NULL pointer.

like image 40
Ryan Avatar answered Sep 18 '22 11:09

Ryan