Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct and typedef in C versus C++

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?

like image 593
user472875 Avatar asked Nov 02 '10 23:11

user472875


2 Answers

typedef struct THIS_IS_A_TAG
{
    int a;
    int b;
} THIS_IS_A_TYPEDEF;

THIS_IS_A_TYPEDEF object1;     // declare an object.       C:Ok,     C++:Ok
struct THIS_IS_A_TAG object2;  // declare another object.  C:Ok,     C++:Ok
THIS_IS_A_TAG object3;         // declare another object.  C:Not Ok, C++:Ok

The reason for the typedef is because C programmers would like to be able to do that third thing, but they can't.

like image 121
Benjamin Lindley Avatar answered Nov 16 '22 03:11

Benjamin Lindley


The difference between:

struct Name {};

And

typedef struct Name {} Name;

Is that, in C, you need to use:

struct Name instance_name;

With the former, whereas with the latter you may do:

Name instance_name;

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 keyword typedef, then you need to supply an alias to which to typedef that name).

As for the last variation:

typedef struct { /* ... */ } Name;

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.

like image 26
Michael Aaron Safyan Avatar answered Nov 16 '22 04:11

Michael Aaron Safyan