开发者

What causes this compiler error in a small modular C program?

I have written the following simple C program:

#include <stdio.h>

int num1, num2;
int sum(int, int);

int main(void);
{
    printf("Enter two numbers:");
    scanf("%d %d", &num1, &num2);
    sum(num1, num2);
    return 0;
}

int sum(int a, int b)
{ 
    i开发者_Go百科nt res;
    res = a + b;
    return res;
}

But it produces the following compiler error:

prog.c:5: error: expected identifier or ‘(’ before ‘{’ token

What could be causing this error, and how can I fix it?


The semicolon after the declaration of the main function:

int main(void);

is being interpreted by the compiler as marking the end of that function. Because the semicolon is there, it doesn't know what to do with the block of code that follows the declaration of that function. That's what the compliation error is telling you:

prog.c:5: error: expected identifier or ‘(’ before ‘{’ token

It doesn't know what to do with the { that comes after the semicolon token, which indicates the end of a statement.

Removing the semicolon is the simple solution; rewrite your main function like this:

int main(void)
{
    printf("Enter two numbers:");
    scanf("%d %d",&num1,&num2);
    sum(num1,num2);
    return 0;
}

As for the problem brought up in the comments:

see when i run the output it asks for entering two numbers and doesnot show any sum result ??

Ah, that's a completely different problem. The code is syntactically correct, so you don't get any more compiler errors, but it's got a logic error! You never told the computer to print the sum of those two numbers to the screen. You need to insert another printf statement, just like the first one that you have. But this time, you want to print the value returned by the sum function.

The final code might look something like this:

int main(void)
{
    printf("Enter two numbers:");
    scanf("%d %d",&num1,&num2);
    printf("%d\n", sum(num1, num2));
    return 0;
}


int main(void); remove the ; from that line.


Try replacing int main(void); with int main(void) (no ";")


There is a semicolon after the prototype of main:

int main(void);

So there is not a definition of main in your program:

int main(void) { /*  */ }

The compiler is expecting either a function name or a struct name before a '{'.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜