0

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.

papezjustin
  • 2,223
  • 6
  • 24
  • 31
  • 2
    possible duplicate of [typedef required in struct declaration](http://stackoverflow.com/questions/17124902/typedef-required-in-struct-declaration) – Oliver Charlesworth Sep 24 '13 at 21:51
  • 1
    Are those C tutorials or C++ tutorials? – luiscubal Sep 24 '13 at 21:52
  • I would say this is a duplicate. My apologies, I tried searching for the answer before posting but I did not include the word "typedef" in my search so the link you have posted did not come up. Thank you. – papezjustin Sep 24 '13 at 21:59
  • `main()` returns `int`, too. Your tutorials seem not so good. – Crowman Sep 24 '13 at 22:00
  • Compiles and runs without int for me; however, I am not arguing that it isn't needed. – papezjustin Sep 24 '13 at 22:03
  • The correctness of C code cannot be ascertained by compiling and running, C doesn't work like that. – Crowman Sep 24 '13 at 22:04
  • I think you misunderstood my first comment, I wasn't arguing as to the "correctness" of the C code, I was simply saying that it compiles and runs without 'int'. – papezjustin Sep 24 '13 at 22:06
  • I know exactly what you were saying, and I was telling you that this fact is not relevant to my comment. The fact it compiles and runs for you tells you nothing about whether or not `main()` is required to return `int`. – Crowman Sep 24 '13 at 22:07

2 Answers2

2

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

ouah
  • 142,963
  • 15
  • 272
  • 331
1

You can get around that by doing

typedef struct test_s 
{
    int num;
} test;
Jesus Ramos
  • 22,940
  • 10
  • 58
  • 88