← The C Language Lesson 44 of 77 · 10 XP

Type aliases: typedef

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

typedef gives a type a new name:

typedef unsigned char byte;
byte b = 255;

typedef struct {
    double x, y;
} vec2;            // now you can simply write vec2, without the word struct

vec2 v = {1.0, 2.0};

For structs that refer to themselves (a list node), the struct's name is still needed:

typedef struct node {
    int value;
    struct node *next;     // the typedef name doesn't exist yet here
} node;

A note on style: the Linux kernel dislikes typedefs for structs (struct task_struct is written out in full, so it's clear that it's a struct). In most other projects typedef struct is the norm. What matters most is consistency within a project.

Another common use is making complicated declarations readable:

typedef int (*compare_fn)(const void *, const void *);

Task. Declare the type vec2 with typedef struct, with the fields x and y (double), and a function vec2 vec_add(vec2 a, vec2 b). The program reads two vectors and prints their sum with one decimal place.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.