User Tools

Site Tools


typedef_and_struct_syntax

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

typedef_and_struct_syntax [2019/04/08 20:11] (current)
Line 1: Line 1:
 +<​code>​
 +
 +// This is declaration of a struct. It can't be re-declared because it
 +// doesn'​t have a name. This is a useless declaration as it does not
 +// allocate memory nor can you reuse it to do so. Generates a warning
 +// from the compilers but is not an error.
 +struct {
 +  int a;
 +  int b;
 +};
 +
 +// This declaration can't be reused but it does allocate memory, creating a variable
 +// named s1.
 +struct {
 +  int a;
 +  int b;
 +} s1;
 +
 +// This names the struct so you can use it to declare structs of the same type later.
 +// Note that this does not allocate memory.
 +struct my_struct_type {
 +  int a;
 +  int b;
 +};
 +
 +// Let's do this again, but declare a variable at the same time. In other words,
 +// this declaration generates a new struct "​type"​ (as above), but also declares
 +// a variable and allocates memory accordingly.
 +struct another_struct_type {
 +  int a;
 +  int b;
 +} s3;
 +
 +// This uses the previous declarations to create some variables, i.e., actually allocate
 +// memory for a named variable.
 +struct my_struct_type s2;
 +struct another_struct_type s3;
 +// At this point, I have defined two different struct types (another_struct_type,​ my_struct_type).
 +// I can reuse these type declarations to declare variables as shown directly above.
 +// I have declared three variables that are structs: s1, s2, s3.
 +
 +// Always having to use the "​struct"​ keyword is a pain, so you can use a typedef so that the
 +// "​struct"​ keyword is part of the type and does not need to be included each time you
 +// declare a variable of that type.
 +
 +typedef struct {
 +  int a;
 +  int b;
 +} yet_another_struct_type;​
 +
 +// Now, I declare a new variable of the above type:
 +
 +yet_another_struct_type s4;
 +
 +// The book has an example in Chapter 8.2 that uses syntax like this:
 +
 +typedef struct one_more_struct_type {
 +  int a;
 +  int b;
 +} one_more_struct_type;​
 +
 +// Now, let's declare a variable of this type:
 +
 +one_more_struct_type s5;
 +
 +// Thus it doesn'​t make much sense to give both the typedef and the struct a name, 
 +// as shown in this example. If you define a typedef, than it makes sense to use
 +// as such as it makes it more convenient. In any case, it appears that you can
 +// use either syntax ("​struct"​ or no "​struct"​ keyword).
 +
 +</​code>​
 +
 +
 +
 +
  
typedef_and_struct_syntax.txt ยท Last modified: 2019/04/08 20:11 (external edit)