0

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!

3
  • See also Undefined, unspecified, and implementation-defined behaviour? Commented Jan 24, 2021 at 7:15
  • one thing that is true for both these programs is that they will produce undefined behaviour as changing constants is not recommended, your compiler will even warn you about it in both programs warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] Commented Jan 24, 2021 at 7:30
  • Does this answer your question? changing const value in C Commented Jan 24, 2021 at 14:02

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.