top of page

Creating Custom Types With Typedef in C

Introduction


Whether you're defining a new data structure or simply redefining a preexisting one, typedef can prove convenient in shortening the length of the type name.


In this blog, we'll go over how to use the typedef and struct keywords with examples.


Typedef


Put simply, typedef allows us to rename a data structure (create an alias) using this syntax:

typedef [original name] [new name];

Suppose I wanted to redefine the type unsigned long long:

typedef unsigned long long uLlong;

The typedef keyword can also be applied to pointers:

typedef char * string;

Similarly, they work with arrays as well:

typedef float floatArr[4];

*In this case, we're not quite aliasing the data type float (which is what it seems), but we're aliasing an array of four floats instead.


Now, I can use this alias / redefinition in my code as if it were an array of floats:

#include <stdio.h>

typedef float floatArr[4];

int main(void)
{
	floatArr arr = { 1, 2, 3, 4};
}

Note how the typedef declaration is above main(), which is the convention in C.


Struct


So what if we wanted to create a new data structure--that is to say, combine existing data structures to act as a single one. That's where the struct keyword comes in.


Suppose I define a person as anything that has a name, number, and age. My custom data type for a person could look something like this:

Now, to use this declaration in main.

A few things to note:

  • the data type we made was named "struct Person"

  • we created a person variable using struct Person

  • in order to access the individual variables within struct Person, we use dot notation (.)


Typedef Struct


But typing "struct Person" each time we need a new Person can be a bit of a hassle. If only we could combine struct and typedef...


Well, it turns out you can in C!

#include <stdio.h>

typedef struct Person
{
	char *name;
	char *number;
	int age;
} Person;

By placing the struct in the middle of the typedef, we're essentially creating the data type just before it is renamed from "struct Person" to just "Person".


If you're confused, the equivalent to this would be:

#include <stdio.h>

struct Person
{
	char *name;
	char *number;
	int age;
}
typedef struct Person Person;

The only difference is, we create the struct directly in the middle of the typedef!


Final Thoughts


Hopefully now you can improve the design and efficiency of your program, even if just by a little, knowing how to define and redefine custom types.


Thanks for reading!

Comments


bottom of page