'Is it possible to set const using a user-input?

When programming in C, is it possible to set a const with a value of a user-input? If so, how?



Solution 1:[1]

you can have that even more directly than in Dadam's answer. (Normally I would have put just in a comment, but it is easier to put that in code directly.)

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;
}

Solution 2:[2]

yes, you can.

#include <stdio.h>
int main()
{
   printf("enter your number : ");
   const int i = scanf("%d",&i)*i;
   printf("%d",i);
}

let me explain how this code works. first you should know the point that scanf() function returns an integer value equal to the no of items it read from the user.

for example:

1) scanf("%d",&a); this statement returns value 1 since it read only one item.

2) scanf("%d %d",&a,&b); this statement returns value 2 since it read two integers a and b.

similarly when we assigned scanf("%d",&i)*i to i it gives the value one multiplied by the value of i(which we given as input). therefore you get the same value of i.

Solution 3:[3]

Linker usually locate global const in read-only space (like code space) and therefore it cannot be changed later on

See comments on local const

Solution 4:[4]

In addition to the other answers (which all say no), you could do some ugly things like

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

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

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

Solution 5:[5]

A const variable is C is technically read only. So one can't set it from user-input

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jens Gustedt
Solution 2
Solution 3
Solution 4
Solution 5 Aditya Naidu