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 through pointers to prevent the modification of values in C

3 Answers

0 votes
#include <stdio.h>

// pointer can change, but the data cannot.

int main() {
    const int value = 5;      // immutable data
    const int *ptr = &value;  // pointer to const int (data cannot change)

    printf("Value through ptr = %d\n", *ptr);

    // *ptr = 10;  // ERROR: cannot modify data through pointer

    int other = 20;
    ptr = &other;  // pointer itself can change

    printf("Now ptr points to %d\n", *ptr);

    return 0;
}



/*
run:

Value through ptr = 5
Now ptr points to 20

*/

 



answered Jun 8 by avibootz
edited Jun 8 by avibootz
0 votes
#include <stdio.h>

// pointer cannot change, but the data can.

int main() {
    int value = 5;
    int * const ptr = &value;  // const pointer to int (pointer cannot change)

    printf("Value = %d\n", *ptr);

    *ptr = 10;  // ✔ allowed: data is mutable
    printf("Modified value = %d\n", *ptr);

    // ptr = NULL;  // ERROR: cannot change a const pointer

    return 0;
}



/*
run:

Value = 5
Modified value = 10

*/

 



answered Jun 8 by avibootz
edited Jun 8 by avibootz
0 votes
#include <stdio.h>

// Neither the pointer nor the data can change.

int main() {
    const int value = 5;

    // Fully immutable: pointer cannot change, data cannot change
    const int * const ptr = &value;

    printf("Value = %d\n", *ptr);

    // *ptr = 10;  // ERROR: data is read-only
    // ptr = NULL; // ERROR: pointer is read-only

    return 0;
}


/*
run:

Value = 5

*/

 



answered Jun 8 by avibootz
edited Jun 8 by avibootz
...