When to use typedef in c?

Can someone tell me when to use typedef in C? In the following code, I get a warning from gcc :

warning: useless storage class specifier in empty declaration

 typedef struct node { int data; struct node* forwardLink; } ; 
+8
c struct typedef
source share
6 answers

So..

You can do it:

 struct node { int data; struct node* forwardLink; }; 

Define an object that can be used as a struct node .

Like this:

 struct node x; 

However, let's say you wanted to call it just node . Then you can do:

 struct node { int data; struct node* forwardLink; }; typedef struct node node; 

or

  typedef struct { int data; void* forwardLink; } node; 

and then use this like:

 node x; 
+10
source share

The syntax of typedef is equal to typedef <type> <name> ; it makes the type available through name . In this case, you specified only type and no name , so your compiler complains.

You probably want

 typedef struct node { int data; struct node* forwardLink; } node; 
+12
source share

Use typedef if you want to use a different name for the type, for example. structure.

In your case, instead of using a struct node to declare a variable, you can instead use only Node as an alias for the struct node .

But you did not specify an alias in your ad:

 typedef struct node { int data; struct node* forwardLink; } Node; 

It does the same, but may better illuminate the cause of your error:

 struct node { int data; struct node* forwardLink; }; // this is equivalent to the above typedef: typedef struct node Node; 
+2
source share
 typedef struct node { int data; struct node* forwardLink; } MyNode; 

If you want to write

 MyNode * p; 

instead

 struct node *p; 

Inside the structure, you still need a struct node * forwardLink;

+1
source share

Typedef is used to determine the type of user data. for example

 typedef int integer; 

Now you can use integer to define int datatype instead of int.

 integer a;// a would be declared as int only 
0
source share

For constants, which are a list of possible values โ€‹โ€‹of a variable:

 typedef enum {BLACK=0, WHITE, RED, YELLOW, BLUE} TColor; 

In general, this helps you understand whether you are manipulating correctly, because compilers will warn you of implicit ebbs, among other things. This is more useful than just making your code more readable.

0
source share

All Articles