Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

change the values of const variable and static const variable in c language

I have two programs:

First program:

#include<stdio.h>
int main()
{
    static const int a = 10;
    int * b;
    b = &a;
    *b = 200;
    printf("%d", a);

    return 0;
}

Second program:

#include<stdio.h>

int main()
{
    const int a = 10;
    int * b;
    b = &a;
    *b = 200;
    printf("%d", a);

    return 0;
}

The first program has a runtime error: "Bus error: 10" but the second one works prefectly. Could you tell me what is the difference between const and static const in these two programs!

question from:https://stackoverflow.com/questions/65867877/change-the-values-of-const-variable-and-static-const-variable-in-c-language

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Both programs execute statements int *b; b = &a; *b = 200; which invokes undefined behaviour because a is a const int and therefore shouldn't be modified. There is no right answer (expected output) — both crashing and not crashing are acceptable results, as is printing 10 or 200 (or lemons and oranges — though that's a little unlikely to happen).

Don't execute anything that causes undefined behaviour!

Your compiler should be complaining; heed its warnings. If it isn't complaining, get a better compiler.

The difference is that the static const int a = 10; variable is placed in a readonly segment (probably part of the text segment, though it really doesn't matter), so the system can spot when you write to it and causes the crash. On the other hand, const int a = 10; is placed on the stack, and the stack is modifiable, so you don't get a crash.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...