Methods in C

Our first example demonstrates how to define and use methods in C. Since C doesn’t have built-in support for methods, we’ll use function pointers to simulate this behavior.

#include <stdio.h>
#include <stdlib.h>

// Define a struct to represent a rectangle
typedef struct {
    int width;
    int height;
} rect;

// Function to calculate the area of a rectangle
int area(rect *r) {
    return r->width * r->height;
}

// Function to calculate the perimeter of a rectangle
int perim(rect *r) {
    return 2 * r->width + 2 * r->height;
}

int main() {
    // Create a rectangle
    rect r = {.width = 10, .height = 5};

    // Call the functions for our struct
    printf("area: %d\n", area(&r));
    printf("perim: %d\n", perim(&r));

    // In C, we always work with pointers explicitly
    rect *rp = &r;
    printf("area: %d\n", area(rp));
    printf("perim: %d\n", perim(rp));

    return 0;
}

In this C code, we define a rect struct to represent a rectangle. We then define two functions, area and perim, which operate on pointers to rect structs.

In the main function, we create a rectangle and demonstrate how to call these functions. Note that in C, we need to pass the address of the struct explicitly when calling the functions.

To compile and run this program:

$ gcc -o methods methods.c
$ ./methods
area: 50
perim: 30
area: 50
perim: 30

C doesn’t have automatic conversion between values and pointers like some other languages. We always need to work with pointers explicitly when we want to avoid copying or allow a function to modify the struct.

While C doesn’t have a direct equivalent to methods or interfaces, we can use function pointers to achieve similar functionality. This approach allows us to create more flexible and reusable code structures.