papezjustin
papezjustin

Reputation: 2355

C struct declaration and initialization

I have been following tutorials from the web on creating a struct and then initializing it in main(). From the tutorials I have followed, I have created my own example, which is as follows:

#include <stdio.h>

struct test {
    int num;
};

main() {
    test structure;
}

However, this does not work:

test.c: In function 'main':
test.c:8: error: 'test' undeclared (first use in this function)
test.c:8: error: (Each undeclared identifier is reported only once
test.c:8: error: for each function it appears in.)
test.c:8: error: expected ';' before 'structure'

But when I change:

test structure;

to:

struct test structure;

the code compiles. Why is this though? From the numerous examples I have looked at it seems that I shouldn't need the 'struct' before 'test structure'.

Thanks for your help/comments/answers.

Upvotes: 0

Views: 276

Answers (2)

ouah
ouah

Reputation: 145829

You were reading C++ examples. In C the type of your structure is struct test not test.

Upvotes: 2

Jesus Ramos
Jesus Ramos

Reputation: 23268

You can get around that by doing

typedef struct test_s 
{
    int num;
} test;

Upvotes: 1

Related Questions