1

我正在学习 C 编程,我的书说,与变量不同,常量在程序执行期间不能更改。并且它们是两种类型的常量 Literal 和 Symbolic。我认为我非常了解 Symbolic。但是字面常量让我感到困惑。它给我的例子是

int count = 20;

我写了这个简单的程序,我可以改变 Literal Constant 的值。

/* Demonstrates variables and constants */
#include <stdio.h>

/* Trying to figure out if literal constants are any different from variables */
int testing = 22;


int main( void )
{
    /* Print testing before changing the value */
    printf("\nYour int testing has a value of %d", testing);

    /* Try to change the value of testing */
    testing = 212345;

    /* Print testing after changing the value */
    printf("\nYour int testing has a value of %d", testing);

    return 0;
}

它输出了这个:

  Your int testing has a value of 22
  Your int testing has a value of 212345
  RUN SUCCESSFUL (total time: 32ms)

有人可以解释这是怎么发生的,我是不是说错了?或者普通变量和文字常量之间有什么区别?

-谢谢

4

3 回答 3

3

字面常量是20. 您可以更改 的值count,但不能将 的值更改为20,例如19

(作为一些琐事,有一些版本的 FORTRAN 你可以做到这一点,所以谈论它并不是毫无意义的)

于 2013-02-25T04:49:27.270 回答
0

在这种情况下,文字是数字22(后来是数字212345)。您将此文字分配给变量testing。这个变量是可以改变的。

当涉及到字符串和字符串文字时,这有点棘手。如果您有一个指向字符串文字的指针,则可以更改实际指针以指向其他字符串,但您可以更改原始指针指向的内容。

例如:

const char *string_pointer = "Foobar";

使用上述定义,您不能执行 eg string_pointer[0] = 'L';,因为这是尝试修改指针指向的文字字符串。


根据上下文,符号常量可以是声明为的“变量”const或预处理器宏。

于 2013-02-25T04:51:29.637 回答
0

C 中的文字常量本身就是任何数字,例如你的20. 你不能通过做,比如说,来改变它20 = 50;。那是非法的。

还有一些常量变量,例如const int blah = 42;。你不能通过blah做类似的事情来改变这一点blah = 100;

但是,如果您有一个正常的非常量变量,例如int foo = 123;,您可以更改它,例如foo = 456;

于 2013-02-25T04:56:17.040 回答