Can't define a function in struct

Tried to google the solution, couldnt find anything.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <stdlib.h>
#include <string.h>


struct student
{

    char name[20];
    char subject[20];
    char College[20];
    unsigned int age;

int bla()
{       //error on this line: error:expected ':', ',', ';', '}' or      '  __attribute__' before '{' token|
    printf("text");  //Just an example.
     return 0;
}

};

int main()
{
struct student simon;
strcpy(simon.name, "Simon");
printf("%s",simon.name);


return 0;
}
This should be allowed as long as you name the file .cpp and not C and build using a C++ compiler.

From your C includes and using C syntax to declare a struct and C function "printf" I suspect that you are trying to define a function inside struct in a C program
Got it. Changed the name of the file, and it worked. thank you. can u explain the reason for it? is that a wrong way to declare in C but a valid one in c++?
your code compiles fine on vs2010. what build system are you using?

EDIT: Note to self, refresh page before posting :)
Last edited on
Got it. Changed the name of the file, and it worked. thank you. can u explain the reason for it? is that a wrong way to declare in C but a valid one in c++?


Functions in structures is a feature of C++, C specification does not have this concept. If you save the file as .c (even if the compiler is capable of compiling C++) the compiler will compile it as a C program.
Topic archived. No new replies allowed.