Fundamental C - typedef
Written by Harry Fairhead   
Monday, 20 July 2020

This extract, from my book on programming C in an IoT context explains the C typedef. You can write good C without knowing anything about it, but you will find it hard to read other people's programs without it and you will be forever mystified about how structs are defined.

 

Cbookcover

Covered in the first part of the chapter and assumed in this extract:

  • The Basic Struct
  • Value Semantics
  • Struct Parameters and Return
  • Pointers to Structs

Using typedef

This extract is from the chapter on structs and it deals with typedef which might seem unconnected with the topic but making structs easier to work with is one of the main uses of typedef. Although it isn’t really anything specifically associated with structs, typedef does tend to be used as a very common alternative way to define them.

A typedef is an alias for a type. For example:

typedef int myinttype;

defines myinttype to be an alias for int. Once defined you can use it as you would int. For example:

myinttype myVar;

declares myVar to be myinttype which is the same as int.

It is easy to misunderstand the way typedef works if you have only seen a simple example. It looks as if myinttype has been made equivalent to int, which is the overall effect, but a typedef is better understood as a modification of the usual declaration. Think of typedef as being a standard declaration where you are not declaring a variable, but an alias for a type. That is:

int myinttype;

declares the variable to be of type int whereas:

typedef int myinttype;

declares myinttype to be a type equivalent to int.

This becomes more easy to understand with more complex examples.

For example:

typedef int *mypinttype;

defines mypinttype to be a pointer to int, but as a type not a variable. After this you can use it as:

mypinttype myPointer;

which declares myPointer as a pointer to int.

For example:

typedef int myArray[20];

declares myArray to be an int array with 20 elements, but as a type. After this you can use it as:

myArray myRealArray;

and myRealArray is an int array with 20 elements.

You can use an alias anywhere you could use the original type and the compiler will not complain if you mix the use of the alias and the type.

Despite the fact that this doesn’t add very much, this use of typedef can make your program more readable if you create type names that are more meaningful - age_t, say. On the other hand, a type alias hides the true type of a variable and as such might make your code harder to understand.

The real value in typedef is when it is used to create a shorter form of a longer type specification. In C there are three ways that such longer type definitions come into play – pointers, function types and structs. In the case of structs the whole point is to eliminate the need to include struct as part of the type name.

For example:

struct point {
    int x;
    int y;
};
typedef struct point point_t;

As a simple declaration, i.e. without typedef, this would make point_t an instance of struct point, but the typedef makes it an alias for the type. Now we can use point_t as an alias for struct point.

For example:

point_t myPoint={0,0};

This saves having to use struct point and you might think that this is a small advantage. However, the use of typedef to define an alias has become so common that many C programmers think it is the only way to create a struct! Combining the two declarations gives:

typedef struct point{
    int x;
    int y;
} point_t;

which looks a lot more like an integrated declaration of a struct rather than a combination of a struct declaration and a typedef – which is what it is. After this declaration you can use struct point or point_t to declare an instance of the struct.

You can also eliminate one of the identifiers by declaring an anonymous struct:

typedef struct{
    int x;
    int y;
} point;

and now it really does look as if this is the form of declaration for a struct.

Notice that you can use:

typedef struct point{
    int x;
    int y;
} point;

if you want as the struct point does not introduce the identifier point but the combined struct point.

The typedef idiom is very commonly used to create a struct but it is important to realize that it is a combination of typedef and a struct declaration.

Notice that:

struct point {
    int x;
    int y;
}myPoint;

creates an instance of point i.e. myPoint is a block of memory but:

typedef struct point {
    int x;
    int y;
}myPoint;

creates a type that has to be used in a declaration, i.e. myPoint is a type with no storage associated with it.

As well as structs, typedefs can make other complex declarations simpler. For example, consider defining a pointer to a particular function:

int *(pFunc)(int, int);

pFunc is a pointer to a function that takes two ints as parameters and returns an int. You can simplify this using:

typedef int *(pFunc_t)(int, int);
pFunc_t pFunc;

where now pFunc_t is a type specifying a pointer to a function that takes two ints and returns an int.

Included in the rest of the chapters:

  • Nested Structs
  • Padding
  • Union
  • Bit Fields

Summary 

  • A struct is a block of memory used to store a set sequence of data types - its fields. It corresponds to the idea of a record.

  • A struct is declared as a type which can be used to create as many instances of the type as required.

  • The fields of a struct are accessed using the dot notation, struct.field, or if you are using a pointer to a struct then you can use the arrow notation, pstruct->field.

  • Structs are assigned using value semantics. That is a copy is created on assignment, or when used as a parameter or returned via a function. The copy is shallow – i.e. any pointers are copied but not memory external to the struct they may point at.

  • A typedef statement can be used to create an alias for a type. It is often used in conjunction with a struct declaration and this can be confusing for the beginner.

  • Structs can be nested. The nested struct has memory allocated for it within the containing struct.

  • A complication of using structs is padding. Extra bytes often have to be added to a struct to make its fields align with word boundaries.

  • A union is a special type of struct that only allocates memory for the largest of its fields. All other fields share the same memory. A union can be used to alias types, that is the same block of memory is treated as different types. This is the only standard based way of achieving type punning.

  • A struct field can be allocated at the bit level. This sounds attractive but implementation differences make it worth avoiding.

  • Harry Fairhead is the also the author of Applying C For The IoT With Linux, Raspberry Pi IoT in C and  Micro:bit IoT in C .

Related Articles

Remote C/C++ Development With NetBeans

Raspberry Pi And The IoT In C

Getting Started With C/C++ On The Micro:bit

Fundamental C: Getting Closer To The Machine

Now available as a paperback and ebook from Amazon.

  1. About C
      Extract Dependent v Independent
                  & Undefined Behavio
  2. Getting Started With C Using NetBeans
  3. Control Structures and Data
  4. Variables
      Extract Variables
  5. Arithmetic  and Representation
      Extract Arithmetic and Representation
  6. Operators and Expression
      Extract: Expressions
      Extract Side Effects, Sequence Points And Lazy Evaluation
      First Draft of Chapter: Low Down Data
  7. Functions Scope and Lifetime
  8. Arrays
      Extract  Simple Arrays
      Extract  Ennumerations
  9. Strings
      Extract  Simple Strings
     
    Extract: String I/O ***NEW!!
  10. Pointers
      Extract  Starting Pointers
      Extract  Pointers, Cast & Type Punning
  11. Structs
      Extract Basic Structs
      Extract Typedef
  12. Bit Manipulation
      Extract Basic Bits
      Extract Shifts And Rotates 
  13. Files
     Extract Files
     
    Extract Random Access Files 
  14. Compiling C – Preprocessor, Compiler, Linker
     Extract Compilation & Preprocessor

Also see the companion volume: Applying C

<ASIN:1871962609>

<ASIN:1871962463>

<ASIN:1871962617>

<ASIN:1871962455>

 

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

Banner


TestSprite Announces End-to-End QA Tool
14/11/2024

TestSprite has announced an early access beta program for its end-to-end QA tool, along with $1.5 million pre-seed funding aimed at accelerating product development, expanding the team, and scaling op [ ... ]



Go At Highest Rank Ever in TIOBE Index
20/11/2024

Go is currently in 7th place in the TIOBE Index for November 2024. Not only is this is the highest position it has ever had, it's percentage rating is almost equal to its all-time-high. Will Go contin [ ... ]


More News

espbook

 

Comments




or email your comment to: comments@i-programmer.info

 

Last Updated ( Monday, 20 July 2020 )