I get this error:
str.c:5:19: error: expected identifier or '(' before 'struct'
when compiling the following code. What is wrong with it?
#include <stdio.h>
struct addpoints (struct point p1, struct point p2){
p1.x += p2.x;
p1.y += p2.y;
return p1;
}
int main(){
struct point{
int x;
int y;
};
struct point p1 = { 13, 22 };
struct point p2 = { 10, 10 };
addpoints (p1,p2);
printf("%d\n", p1.x);
}
struct
is not a type.struct point
is a type.Also declare your
struct point
type before using it, here you are declaringstruct point
inmain
function.Many problems:
At the first glance, I was surprised, I don't remember C has this syntax? I must be stupid again. Then I see, it is a function, and return type is struct, which is apparently wrong.
struct is a keyword to declare a struct, not a type. If you want to return a struct type, you need the struct name. In your case, you should use:
Also your
struct point
is inside your main function, not global. So a global function likeaddpoints
cannot access it. You must take it outside, and has to be before function addpoints. Because C parser uses up-to-down to parse the code. If you have something that never appear before the usage, it will tell you,first declaration of something
It looks like you want
addpoints
to return astruct point
, but you forgot to put inpoint
afterstruct
:However, this will still not work unless you pull your definition of
struct point
out ofmain
: