csettergetter

Getters and setters in pure C?


Can I use getters and setters in pure C instead of using extern variables?


Solution

  • First of all, don't listen to anyone saying "there is no object-orientation in language x" because they have truly not understood that OO is a program design method, completely apart from language syntax.

    Some languages have elegant ways to implement OO, some have not. Yet it is possible to write an object-oriented program in any language, for example in C. Similarly, your program will not automagically get a proper OO design just because you wrote it in Java, or because you used certain language keywords.

    The way you implement private encapsulation in C is a bit more crude than in languages with OO support, but it does like this:

    // module.h

    void set_x (int n);
    int get_x (void);
    

    // module.c

    static int x; // private variable
    
    void set_x (int n)
    {
      x = n;
    }
    
    int get_x (void)
    {
      return x;
    }
    

    // main.c

    #include "module.h"
    
    int main (void)
    {
      set_x(5);
      printf("%d", get_x());
    }
    

    Can call it "class" or "ADT" or "code module" as you prefer.

    This is how every reasonable C program out there is written. And has been written for the past 30-40 years or so, as long as program design has existed. If you say there are no setters/getters in a C program, then that is because you have no experience of using C.

    EDIT: For completeness, the thread-safe, multi-instance version of the above is also possible using "opaque type", see How to do private encapsulation in C?