Is it possible to set const using user input?

When programming in C, can I set const with a user input value? If so, how?

+4
source share
6 answers

Why not?

 void some_function(int user_input) { const int const_user_input = user_input; ... return; } int main (void) { int user_input; scanf("%d", &user_input); some_function(user_input); return 0; } 
+8
source

you can have it even more directly than in Dadam’s answer. (Normally, I would put it only in comments, but it’s easier to do it directly in the code.)

 int get_user_input(void) { int user_input; scanf("%d", &user_input); return user_input; } int main(void) { int const user_input = get_user_input(); ... return 0; } 
+5
source

Typically, the linker finds the global constant in read-only space (for example, in code space) and therefore cannot be changed later

See comments on local const

0
source

In addition to the other answers (which everyone says no), you can do some ugly things like

 static const int notsoconst = 3; scanf("%d", ((int*) &notsoconst)); 

But this could compile, but maybe it would work at runtime (and undefined behavior in the C language specification), because notsoconst would be placed in a read-only segment (at least with GCC on Linux).

Even if it is doable, I do not recommend coding this way. And even if your implementation does not put constants in some read-only segment, the compiler is allowed to expect that const will never change (as specified in the language standard) and it is allowed to optimize this assumption.

0
source

The constant variable C is technically read-only. Therefore, you cannot install it from user input

-1
source

No, const at compile time. You must take your own measure to force const to be used at runtime.

-1
source

Source: https://habr.com/ru/post/1380141/


All Articles