How to enforce immutability inside a struct to prevent the modification of values in C

1 Answer

0 votes
#include <stdio.h>

// Struct with immutable fields
// Immutability inside a struct

typedef struct {
    const int id;                 // immutable integer
    // const char *name;          // pointer to immutable char, BUT pointer itself is NOT const
    const char * const name;      // immutable pointer to immutable string
} User;

int main() {
    User u = { 520, "Emma" };

    printf("User ID: %d\n", u.id);
    printf("User Name: %s\n", u.name);

    // u.id = 948;        // ERROR: cannot modify const int
    // u.name = "Tom";    // ERROR: pointer is const
    // u.name[0] = 'X';   // ERROR: data is const

    return 0;
}



/*
run:

User ID: 520
User Name: Emma

*/

 



answered Jun 8 by avibootz
...