1

I want to know the difference between local and global constants because I tried these examples and there are different results

in this example

#include <stdio.h>

const int  x = 5;

int main()
{
    int* ptr = &x;
    *ptr= 10;
    printf("%d",*ptr);
}

it returns segmentation fault

but in this example x changes and i know this way

#include <stdio.h>

int main()
{
    const int  x = 5;
    int* ptr = &x;
    *ptr= 10;
    printf("%d",*ptr);
}
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • It should be a compilation error. What compiler do you use? – smitsyn Nov 03 '19 at 14:32
  • 4
    Although your compiler did compile both programs, it issued a warning message each time. That should've been your first clue that the program is broken and consists of undefined behavior. As such, you cannot expect your program to have any particular result. See the linked question for more information. – Sam Varshavchik Nov 03 '19 at 14:33
  • As long as your program doesn't misbehave (like your two do) then the difference is about locality and linkage, which could make a difference about where the compiler might store the variables. – Some programmer dude Nov 03 '19 at 14:34
  • @smitsyn GCC compiler – Ahmed Sharaf Nov 03 '19 at 14:35
  • Neither the C language nor the C++ language are nanny languages. Avoid undefined behavior, and then you'll only have to deal with well behaved bugs. Go out of your way to do undefined behavior, and you'll have to deal with hard-to-reason-about bugs. – Eljay Nov 03 '19 at 14:44
  • What version and parameters? Check for yourself at https://godbolt.org/z/8UXGt_ . The code you presented is invalid. These are hard compilation errors, that is all you should know about both cases. There are many differences between local and global constant variables, but none are related to your question. – smitsyn Nov 03 '19 at 14:50
  • Undefined behaviour is *undefined*. Don't try to reason about a broken program. The compiler is allowed to do *anything* when you break the rules. And yes, C++ has the novel failure mode of having false positives for asking the compiler "is this a program?". – Jesper Juhl Nov 03 '19 at 15:23

0 Answers0