开发者

Isn't const supposed to be constant?

Check out this code

#include<stdio.h>

int main()
{

 const int a=7;
 int开发者_StackOverflow社区 *p=&a;
 (*p)++;
 printf("*p=%d\np=%u\na=%d\n&a%u",*p,p,a,&a);
 getch();
}

The output you get for this is

*p=8
p=1245064
a=8
&a1245064

How is this possible?? We declared variable a as constant. Doesnt this mean that the location pointed to by a can never be changed during the course of pgm execution??


That's undefined behavior - in your case it is working as you described, but it could just as well crash the program or cause any other problems. In your case const doesn't prevent the compiler from allocating the variable in modifiable memory, so you technically can modify it by obtaining a pointer to that variable and working through the pointer.


Undefined behaviour is not to be relied upon ;-)


Would you really want to use C if it actually prevented that from working? The fact it works that way is very much in the spirit of the language.


Reading your comment "it only gives a warning saying suspicious pointer conversion" it should be clear enough to deduce that you are doing something illegal.

You are assigning to a int * variable a const int * value.

The fact that C hasn't any runtime checkings to prevent you from modifying that memory address doesn't imply that it's allowed! (and in fact, the static type system checking is telling you that).


If yours doesn't detect this automatically, just get yourself a decent compiler. E.g clang gives me 4 problems with your code:

clang    -c -o test-const.o test-const.c
test-const.c:17:7: warning: initializing 'int const *' discards qualifiers, expected 'int *' [-pedantic]
 int *p=&a;
      ^ ~~
test-const.c:19:20: warning: conversion specifies type 'unsigned int' but the argument has type 'int *' [-Wformat]
 printf("*p=%d\np=%u\na=%d\n&a%u",*p,p,a,&a);
                  ~^                 ~
test-const.c:19:32: warning: conversion specifies type 'unsigned int' but the argument has type 'int const *' [-Wformat]
 printf("*p=%d\np=%u\na=%d\n&a%u",*p,p,a,&a);
                              ~^         ~~
test-const.c:20:2: warning: implicit declaration of function 'getch' is invalid in C99 [-Wimplicit-function-declaration]
 getch();
 ^
4 diagnostics generated.

These are all serious problems.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜