Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ void prefixed to a function call. eg. `main() {void func();}`

void func() {assert(0);}
int main () {void func();}

The above code does not call func(), or at least does not reach the assertion. Not that I really need to know, but I'm just curious, what is going on here?

like image 378
Matt Munson Avatar asked Dec 02 '22 02:12

Matt Munson


1 Answers

You're declaring a prototype for a function named func which returns nothing and takes no arguments. That's (one of) the subtle difference between function calls and function prototypes. Notice that the line above main, the void func() {assert(0);}, has no effect on whether this is a prototype or a call. You could remove it and the code would do the same thing - that is, nothing.

This also tells you that you can redeclare function prototypes. You could even have this:

int main() {
    void blah();
    void blah();
    void blah();
    void blah();
}

And the code would still do what it did before - nothing.

If you leave off the void, it would call the function.

Also, notice that in the case of a function which takes parameters, this:

int main() { func(4); }

would not turn into a prototype if you added void before it like this:

int main() { void func(4); }

it would just produce a syntax error.

like image 121
Seth Carnegie Avatar answered Dec 05 '22 18:12

Seth Carnegie