Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 answers

573 users

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
...