Search code examples
cvariable-declarationfunction-declaration

Should int a, f() {} compile?


for a typo, I leave the a in there. When I went to compile, the compiler reported:

missing a ',' between declaration of 'a' and 'f'

code:

int a
f(void) 
{
}

And was very surpresing since I've never get any error message like this and I didn't know I could put a comma there and it just compiled fine(in more than one compiler I tested):

int a,
f(void) 
{
}

But of course it wasn't my intention but int f(void){} instead of. I give a try in another compilers but it didn't worked and reported a syntax error like this (in clang):

error: expected ';' after top level declarator.

My question is: which one is correct? it should or shouldn't compile? what does standard says about that behavior?

I'm not going to use it since it's a bit ugly to put variable and functions split by comma (just like it is for a function prototype). I'm just curious.

EDIT: added void in function parameter. Actually I wanted to write a function with empty parameters


Solution

  • No it should not compile

    You need

    int a;
    void f(void)
    {
    }
    

    the voids are not the most important part at this moment in time. The most important part is that you didn't put a semicolon after a.

    When you don't put a semicolon after int a the compiler keeps reading in the next lines as part of the int declaration, so it didn't detect that you had two things you wanted, but rather one very weird thing like

    int a f() { }
    

    By adding a comma, you still didn't fix the issue; because, a comma indicates a list which would be a valid way to declare a list of integers

    int a, b;
    

    is valid while

    int a, f() { }
    

    is not because f() { } is not a valid name for an integer. Characters like that might be valid in other places, but the preceding a, prevents it from being a valid there either. The combination of what was meant to be two lines prevents it from being valid C.

    But by adding a semicolon, now you get two sensible things in C.

    int a;
    f() { }
    

    I highly recommend that every function you write has a return value, even if it returns nothing.

    int a;
    void f() { }
    

    and again, it is a very good practice to explicitly indicate that the function doesn't take any parameters, so

    int a;
    void f(void) { }
    

    which is equivalent to

    int a;
    void f(void)
    {
    }