0

I have the following code: I am inserting appropriate comments.

#include <stdio.h>
int main(void)
{
char *x = "Hello"; //x points to a constant string
*x = 'B'; //Runtime error

char str[10] = "Hello"; //String is not constant
x = str; //x now points to a non-constant string
*x = 'B'; //Hence this is allowed.
}

So is it that the value to which a pointer points is checked for its constantness at runtime, and an error is thrown accordingly.

user2684198
  • 812
  • 1
  • 10
  • 18
  • 1
    Haven't you answered your own question? – jwodder Jul 09 '14 at 20:40
  • 1
    “So is it that the value to which a pointer points is checked […]”—this is C, nothing about such things is checked, _you_ are responsible for what you do. The compiler _assumes_ you don't change the string (or try to do so). You promised not to even try. Undefined behavior means: It may work sometimes on some systems, it may be defined on some systems or whatever, but you cannot rely on it (at least not portably). If you want the compiler to be able to help you: Write `const char *x = "Hello";`. – mafso Jul 09 '14 at 21:04

0 Answers0