代码之家  ›  专栏  ›  技术社区  ›  Laz

常数不应该是常数吗?

c
  •  2
  • Laz  · 技术社区  · 15 年前

    #include<stdio.h>
    
    int main()
    {
    
     const int a=7;
     int *p=&a;
     (*p)++;
     printf("*p=%d\np=%u\na=%d\n&a%u",*p,p,a,&a);
     getch();
    }
    

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

    这怎么可能??我们将变量a声明为常量。这是否意味着在pgm执行过程中,a指向的位置永远不能更改??

    5 回复  |  直到 12 年前
        1
  •  5
  •   sharptooth    15 年前

    这是未定义的行为-在您的情况下,它正按照您所描述的那样工作,但它也可能使程序崩溃或导致任何其他问题。对你来说 const 不会阻止编译器在可修改内存中分配变量,因此技术上可以通过获取指向该变量的指针并遍历该指针来修改它。

        2
  •  3
  •   domen    15 年前

    不可依赖未定义的行为;-)

        3
  •  1
  •   Kendall Helmstetter Gelner    15 年前

    如果C真的阻止了它的工作,你真的想用它吗?它以这种方式工作的事实在很大程度上符合语言的精神。

        4
  •  1
  •   fortran    15 年前

    阅读您的评论“它只会给出一个警告说可疑的指针转换”应该足够清楚地推断出您正在做一些非法的事情。

    int * const int *

    事实上,C没有任何运行时检查来阻止您修改内存地址并不意味着它是允许的(实际上,静态类型系统检查告诉您)。

        5
  •  1
  •   Jens Gustedt    15 年前

    如果你的没有自动检测到这个,那就给自己找一个像样的编译器。例如,clang给了我4个代码问题:

    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.
    

    这些都是严重的问题。