SyntaxStudy
Sign Up
C Defining Structs and typedef
C Beginner 1 min read

Defining Structs and typedef

A struct is a user-defined type that groups variables of different types under a single name. Where an array holds multiple values of the same type, a struct holds logically related values that may differ in type — a `Point` struct might hold two `double` values, while an `Employee` struct might hold a name, an ID, and a salary. Struct members are accessed with the dot operator `.`. The `typedef` keyword creates an alias for a type, making declarations cleaner. Without `typedef`, you must write `struct Point p;` every time. With `typedef struct { double x; double y; } Point;`, you can write just `Point p;`. Many C codebases use `typedef` for all struct types to reduce verbosity. The two styles can be mixed: `typedef struct Node { struct Node *next; int value; } Node;` uses the tag `Node` for the self-referential pointer and the typedef `Node` for external use. Structs are value types in C. Assigning one struct to another performs a shallow copy of all members. Passing a struct to a function passes a copy, so changes inside the function do not affect the original. For efficiency and to allow modification, large structs are typically passed and returned by pointer. The arrow operator `->` combines dereference and member access: `ptr->member` is equivalent to `(*ptr).member`.
Example
#include <stdio.h>
#include <string.h>

/* Struct with typedef */
typedef struct {
    double x;
    double y;
} Point;

typedef struct {
    char   name[64];
    int    id;
    double salary;
} Employee;

/* Pass by pointer for efficiency */
void give_raise(Employee *emp, double percent)
{
    emp->salary *= (1.0 + percent / 100.0);
}

double distance(Point a, Point b)
{
    double dx = a.x - b.x;
    double dy = a.y - b.y;
    /* Approximation without <math.h> for brevity */
    double sq = dx * dx + dy * dy;
    /* Newton-Raphson sqrt approximation */
    double r = sq;
    for (int i = 0; i < 20; i++)
        r = (r + sq / r) / 2.0;
    return r;
}

int main(void)
{
    Point p1 = {0.0, 0.0};
    Point p2 = {3.0, 4.0};
    printf("Distance: %.2f\n", distance(p1, p2));  /* 5.00 */

    Employee emp;
    strncpy(emp.name, "Alice", sizeof(emp.name) - 1);
    emp.id     = 101;
    emp.salary = 50000.0;

    printf("Before raise: %.2f\n", emp.salary);
    give_raise(&emp, 10.0);
    printf("After 10%% raise: %.2f\n", emp.salary);

    /* Struct assignment (shallow copy) */
    Employee copy = emp;
    copy.salary = 1.0;
    printf("Original salary unchanged: %.2f\n", emp.salary);

    return 0;
}