简体   繁体   中英

error C2143: syntax error: missing ';' before '{' in C

Currently I am experiencing a very odd C error. When I try to compile the following .c code:

 #include <stdio.h>
int main() {

    int five() {
        return 5;
}

for (int i = 0; i < 10; i++) {
    printf("%d ", five());
    }

    return 0;
}

, I obtain the following error:

error C2143: syntax error: missing ';' before '{' in C

I think something is wrong with my compiler but what?

I am using Visual Studio Community 2017 on Windows 10 and its developer command line. So my compiler is cl.

Glad to hear if someone has a clue.

Is this what you want to achieve?

#include <stdio.h>
int five() {
        return 5;
    }
int main() {
    for (int i = 0; i < 10; i++) {
    printf("%d ", five());
    }
    return 0;

}

The compiler works "token" by "token". After int main() { it sees the tokens int , five , ( and ) which are part of a declaration of function five (returning int and accepting an unspecified, but fixed, number of arguments). This declaration is completed with the token ; but the next available token is { which makes the whole thing invalid syntax.

TLDR: nested functions are illegal in C.

Properly formatted, with some start-end comments for clarity.

#include <stdio.h>

int five()   /* Start of Function FIVE */
{
    return 5;
}            /* End of Function FIVE */



int main()   /* Start of MAIN */
{
    for (int i = 0; i < 10; i++)
    {
        printf("%d ", five());
    }

    return 0;
}             /* End of MAIN */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM