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.

8
  • 2
    possible duplicate of typedef required in struct declaration Commented Sep 24, 2013 at 21:51
  • 1
    Are those C tutorials or C++ tutorials?
    – luiscubal
    Commented Sep 24, 2013 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. Commented Sep 24, 2013 at 21:59
  • main() returns int, too. Your tutorials seem not so good.
    – Crowman
    Commented Sep 24, 2013 at 22:00
  • Compiles and runs without int for me; however, I am not arguing that it isn't needed. Commented Sep 24, 2013 at 22:03

2 Answers 2

2

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

1
  • Thank you! Will accept your answer as the correct answer shortly (currently have to wait 11 minutes). Commented Sep 24, 2013 at 21:55
1

You can get around that by doing

typedef struct test_s 
{
    int num;
} test;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.