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!

Mori
  • 13
  • 1
  • See also [Undefined, unspecified, and implementation-defined behaviour?](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior) – Jonathan Leffler Jan 24 '21 at 07: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]` – Palash Nigam Jan 24 '21 at 07:30
  • Does this answer your question? [changing const value in C](https://stackoverflow.com/questions/3709548/changing-const-value-in-c) – fdcpp Jan 24 '21 at 14:02

1 Answers1

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278