I am currently using a C++ IDE for something that will need to work on C, and wanted to make sure that I won't have problems with this later on. After making the struct below:
typedef struct test {
int a;
int b;
};
I then create an instance of it using
test my_test;
then stuff like my_test.a = 5
, etc... and this works fine in my VStudio C++.
Is this going to work on gcc
later on?
I read the related questions that popped up (I see I am not the first person with this kind of question, either) but no one seemed to use the way I did.
In fact, what is the difference between typedef struct {//stuff} test;
and my version?
The reason for the typedef is because C programmers would like to be able to do that third thing, but they can't.
In both C and C++, the example construct is modestly pointless:
In C, this says there is a type
struct test
with the two integers as content. If there was a name between the close brace '}
' and the semi-colon ';
', then you would get some benefit from the keywordtypedef
; as it stands, the keywordtypedef
is redundant, and (if set fussy enough), GCC will warn you about it.In C++, this says there is a type
struct test
; further, in C++, it creates a typetest
too (which does not happen in C). The keywordtypedef
can still be left out and the same result will be achieved.The syntax is legal; it is not useful, that's all. The keyword
typedef
can be omitted without changing the program's meaning in the slightest.You can do:
Now, in both C and C++, you have a type
struct test
and an alias for ittest
.The difference between:
And
Is that, in C, you need to use:
With the former, whereas with the latter you may do:
In C++, it is not necessary to repeat the
struct
keyword in either case. Note that your example in which you create a typedef with no name (i.e.typedef struct Name{};
) is non-standard AFAIK (if you use the keywordtypedef
, then you need to supply an alias to which to typedef that name).As for the last variation:
The code above creates an unnamed struct that is aliased to Name. You would use such a struct just the same way you would with
typedef struct Name { /* ... */ } Name;
, however compilers often emit the name of the struct (not the alias), and so you may get better error messages involving the struct if you give it a name and typedef that as opposed to typedef'ing an anonymous struct.