boyang
boyang

Reputation: 707

Is this code segment legal in C?

function wait() is declared in another function. Is it legal?

void panic(const int reason, const char *strg) 
{
int ErrNo;
struct machine_attributes mach;
int ret, docstat, cnt;
pid_t pid, wait(int *), setsid(void); 
    ......
}

Thank you!

Upvotes: 4

Views: 176

Answers (2)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215221

Yes it is legal C, and it could be useful in rare cases, for instance if you have a plain C (non-POSIX-oriented) source file that uses wait with static linkage for a function of its own, and suddenly realize you need to call the POSIX wait from a function in that file. By scoping the declaration in the function that calls it, you avoid conflicting with the file-scope static definition of wait.

Note that pid_t may be obtained from other headers that do not declare wait (or any functions), but in other cases you might not be able to use a trick like this due to missing types.

And yes, some may call this a horrible hack/abuse of the language. :-)

Upvotes: 0

CB Bailey
CB Bailey

Reputation: 791759

Yes, so long as this declaration matches the actual definition of the function.

pid_t pid, wait(int *), setsid(void);

This declares three entities: a pid_t named pid, a function (taking int* and returning pid_t) named wait and a function (taking no parameters and returning pid_t) named setsid.

The declaration of pid is also a definition.

Upvotes: 6

Related Questions