top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

C: Is constant variable initialized at the compile time?

+2 votes
518 views

I assume that constant must be initialized to a constant value at compile time, but following code the return value of ge_const() is assigned to x which will be collected at run time. So this must cause an error but I am getting the output as 50. Can someone clarify the detail?

main()
{
    const int x = get_const();
    printf("%d", x);
}
int get_const()
{
    return 50;
}
posted Sep 15, 2014 by Udita

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+2 votes

In this case your constant variable is auto constant not the static constant.
For auto const this is a perfectly valid statement.

answer Sep 15, 2014 by Salil Agrawal
0 votes

Ya you are right.
But in the above code, you are initializing "const int x" at the time of declaration. That's why you are getting a result of 50.

I think you what you need is,
just do this.
1. declare the const int x; and then try to initialize,
2. x = get_const(); //here you will get a compilation error saying that assignment of read-only variable ‘x’.

int main()
{
    const int x;
    x = get_const();
    printf("%d", x);

    return 0;
}

int get_const()
{
    return 50;
}
answer Sep 15, 2014 by Arshad Khan
...