Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 262 Vote(s) - 3.54 Average
  • 1
  • 2
  • 3
  • 4
  • 5
typedef struct vs struct definitions

#1
I'm a beginner in C programming, but I was wondering what's the difference between using `typedef` when defining a structure versus not using `typedef`. It seems to me like there's really no difference, they accomplish the same goal.


struct myStruct{
int one;
int two;
};

vs.

typedef struct{
int one;
int two;
}myStruct;
Reply

#2
In C (not C++), you have to declare struct variables like:

struct myStruct myVariable;

In order to be able to use `myStruct myVariable;` instead, you can `typedef` the struct:

typedef struct myStruct someStruct;
someStruct myVariable;

You can combine `struct` definition and `typedef`s it in a single statement which declares an anonymous `struct` and `typedef`s it.

typedef struct { ... } myStruct;
Reply

#3
The difference comes in when you use the `struct`.

The first way you have to do:

struct myStruct aName;

The second way allows you to remove the keyword `struct`.

myStruct aName;
Reply

#4
With the latter example you omit the struct keyword when using the structure. So everywhere in your code, you can write :

myStruct a;

instead of

struct myStruct a;

This save some typing, and might be more readable, but this is a matter of taste

Reply

#5
The `typedef`, as it is with other constructs, is used to give a data type a new name. In this case it is mostly done in order to make the code cleaner:

struct myStruct blah;

vs.

myStruct blah;
Reply

#6
Another difference not pointed out is that giving the struct a name (i.e. struct myStruct) also enables you to provide forward declarations of the struct. So in some other file, you could write:

struct myStruct;
void doit(struct myStruct *ptr);

without having to have access to the definition. What I recommend is you combine your two examples:

typedef struct myStruct{
int one;
int two;
} myStruct;

This gives you the convenience of the more concise typedef name but still allows you to use the full struct name if you need.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through