Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you specify variables to be final in C? [duplicate]

Tags:

c

final

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?

like image 548
cs95 Avatar asked Jun 08 '17 13:06

cs95


People also ask

What is final instance variable?

The final modifier is used for finalizing the implementations of classes, methods, and variables. A final instance variable can be explicitly initialized only once. A final instance variable should be initialized at one of the following occasions − At time of declaration. In constructor.

What happens if the variable is final?

Final variables If a variable is declared with the final keyword, its value cannot be changed once initialized.

Can final variables be changed?

The only difference between a normal variable and a final variable is that we can re-assign the value to a normal variable but we cannot change the value of a final variable once assigned.

Can final object be modified?

final means that you can't change the object's reference to point to another reference or another object, but you can still mutate its state (using setter methods e.g). Whereas immutable means that the object's actual value can't be changed, but you can change its reference to another one.


1 Answers

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.

like image 186
tilz0R Avatar answered Nov 06 '22 03:11

tilz0R