6

I am aware that it is possible to declare constants using the #define macro. With this, it would be simple to define integer, floating point or character literals to be constants.

But, for more complicated data structures, such as an array, or a struct, say for example:

typedef struct {
    int name;
    char* phone_number;
} person;

I want to be able to initialise this just once and then make it a non-editable struct.

In object oriented languages, there exists the final keyword to do this easily, but there is no such thing in C. One workaround I've thought of is to use setjmp and longjmp to simulate try-catch braces and do a rollback if a change is detected. You'd need to store a backup in a file/in memory object, which can get little messy if you have many such objects you want to protect from accidental alteration.

Q: Is it possible to effectively represent such a pattern in C? If yes, how can it be done?

Community
  • 1
  • 1
cs95
  • 379,657
  • 97
  • 704
  • 746
  • Please remove the `c99` tag since declaring a variable constant is possible since the beginning of C programming. – Badda Jun 08 '17 at 13:38
  • Sure. Removed that tag. – cs95 Jun 08 '17 at 13:39
  • @Badda "_final is a common keyword specifying that the reference declared as final cannot be modified once it is initialized._" From the description of the tag. – cs95 Jun 08 '17 at 13:43
  • *In object oriented languages, there exists the final keyword to do this easily* there's no `final` in C++, C#, python... – phuclv Jun 16 '19 at 08:45

3 Answers3

14

Use const as keyword for variable. This is a way how to prevent value to be modified later.

const int a = 5;
a = 7; //Error, you cannot modify it!

For example, in embedded systems where you have flash memory, this variable may be put to flash by linker, if available. But it is not necessary the case.

unalignedmemoryaccess
  • 7,246
  • 2
  • 25
  • 40
1

The equivalent keyword in C is const.

MrPromethee
  • 721
  • 9
  • 18
1

const is the way to go. const is a keyword that might tell the compiler two things:

  1. Enforce the constantness of an object.

    const YourType t;
    

    Declares a non-modifiable object. The compiler will force the const-correctness. It is important to note that the const-correctness is enforced conceptually by the compiler and there are ways to elude those rules.

  2. constantness of pointer (or to an access to an object)

    const int* pointer
    

    Declares a const pointer to an int (which is not const). It means that if there is a non-const pointer to that int then it can be modified.

For more info see this great answer.

cs95
  • 379,657
  • 97
  • 704
  • 746
Davide Spataro
  • 7,319
  • 1
  • 24
  • 36