Cprogramming 简明教程

C - Constants

constant 中的 C 对于内存中的一个位置给予用户分配的名称,一旦声明之后就不能修改它的值。这就跟 C 中的 variable 相反。 variable 也同样是已命名的内存位置,但是它的值在代码进行过程中可以改变。

A constant in C is a user-assigned name to a location in the memory, whose value cannot be modified once declared. This is in contrast to a variable in C, which is also a named memory location, however whose value may be changed during the course of the code.

为了避免在程序中反复使用硬编码值,建议定义一个常量并使用它。C 程序中的 Constants 通常被用来引用一个值,但是如果这个值在程序中重复使用,同时它的值很可能不会改变,那么就会容易出错。

Instead of repeatedly using hard-coded values in a program, it is advised to define a constant and use it. Constants in a C program are usually employed to refer to a value which may be error-prone if it is to be used repetitively in the program, at the same time its value is not likely to change.

举例来说,数学常数 PI 的值是一个高精度的浮点数:3.14159265359。如果它很可能频繁出现,就可以将它声明为一个常量并通过它的名称来使用。

For example, the value of mathematical constant PI is a high-precision floating point number 3.14159265359, and if it is likely to appear frequently, it is declared as a constant and used by its name.

我们可以将 C 中的常量看作一个只读变量,因为它的值只能在之后使用,而不能被修改。

We may consider a constant in C as a read-only variable, as its value can only be used subsequently but cannot be modified.

你可以使用以下两种方式在 C 程序中声明一个常量:

You can declare a constant in C program with either of the following two ways −

  1. Using the const Keyword

  2. Using the #define Directive

让我们来了解一下在 C 中声明常量的这两种方式。

Let’s understand these two ways of declaring a constant in C.

Defining a Constant Using the const Keyword

声明常量的语法如下:

The syntax of declaring a constant is as follows −

const type NAME = val;

例如,

For example,

const float PI = 3.14159265359;

我们现在可以在任何表达式中使用 PI,就像我们使用其他变量一样。

We can now use PI in any expression, as we would use any variable.

Example

请看以下示例:

Take a look at the following example −

#include <stdio.h>

int main(){
   const float PI = 3.14159265359;
   float radius = 5;
   float area = PI*radius*radius;
   printf ("area: %f", area);
   return 0;
}

运行这段代码,你会得到以下输出:

On running this code, you will get following output −

area: 78.539818

然而,修改一个常量的值是被禁止的。以下语句会导致编译器错误:

However, changing the value of a constant is prohibited. The following statement gives a compiler error −

const float PI = 3.14159265359;
PI=22/7;

这里,你将得到以下 error message

Here, you will get the following error message

error: assignment of read-only variable 'PI'

对于 variables ,你可以在程序中声明一个变量并在之后为它分配一个值,然而对于一个常量你不能遵循相同的方法。

In case of variables, you can declare a variable and assign it a value later on in the program, however you cannot follow the same process in case of a constant.

你可以在 C 中声明一个常量而不为它分配一个值。但当你在之后尝试为它分配一个值的时候,编译器就会抛出一个错误。

You can declare a constant in C without assigning it a value. But when you try to assign it a value afterwords, then the compiler will throw an error.

const float PI;
PI = 3.14159265359;

这里,你将得到以下错误信息:

Here, you will get this error message −

error: assignment of read-only variable 'PI'

Note : "sizeof" 返回 "size_t"。"size_t" 的无符号整数类型会因平台而异。并且,它可能并非各处的 long 无符号 int。在这些情况下,我们对格式化字符串使用 "%zu" 而不是 "%d"。

Note: "sizeof" returns "size_t". The type of unsigned integer of "size_t" can vary depending on platform. And, it may not be long unsigned int everywhere. In such cases, we use "%zu" for the format string instead of "%d".

这是因为 compiler 在声明时赋值了一个随机垃圾值,之后你不能再改变它。因此,你必须一次性声明并初始化常量。

This is because the compiler assigns a random garbage value at the time of declaration, which you cannot change afterwards. Hence, you must declare and initialize the constant at once.

C 中的 constant 可以是任何 data types ,包括 int、float、char 等基本数据类型,以及 struct 等派生数据类型。

A constant in C can be of any of the data types including primary data types such as int, float, char, and derived data types such as struct.

Defining a Constant Using the

使用 #define preprocessor directive 也是定义常量的有效方法。以下是它的 syntax

Using the #define preprocessor directive is also an effective method to define a constant. Here is its syntax

#define name = value

来看一下以下示例:

Take a look at the following example:

#define PI = 3.14159265359

尽管如此定义的常量也可以在任何表达式中使用(就像使用 const 关键字的常量一样),但是有一个 difference between the two

Although the constant so defined can also be used in any expression (just as the one with the const keyword), there is a difference between the two.

通过 #define 指令创建的常量不受编译器处理。它们的行为像宏,其值在运行时进行替代。

The constants created by the #define directive are not handled by the compiler. Instead, they behave as macros, whose values are substituted at the runtime.

另一个明显的区别是,在使用 #define 指令时,无需提及要赋予常量的值的数据类型。

The other notable difference is that you need not mention the data type of the value to be assigned to the constant when using the #define directive.

Example: Define a Constant Using the

下面给出使用 #define 指令定义的常量的另一个示例 −

Given below is another example of a constant defined using the #define directive −

#include <stdio.h>
#define LENGTH 10
#define WIDTH  5
#define NEWLINE '\n'

int main() {
   int area;
   area = LENGTH * WIDTH;
   printf("length: %d width: %d", LENGTH, WIDTH);
   printf("%c", NEWLINE);
   printf("value of area : %d", area);
   return 0;
}

在运行此代码后,您将获得以下输出 −

Upon running this code, you will get the following output −

length: 10 width: 5
value of area : 50

因为常量也是 C 中的一个 identifier ,所以它遵循形成标识符的所有规则。C 中的标识符区分大小写。因此在 C 中定义常量时遵循的惯例是使用大写字符,但这不是强制性的。

Since a constant is also an identifier in C, it follows all the rules of forming an identifier. Identifiers in C are case-sensitive. Hence the convention followed while defining a constant in C is that it uses uppercase characters, however it is not mandatory.

Changing the Value of a Constant

根据定义,常量是不变的。你首先会为什么要更改常量?我们使用的是假设要保持不变的常量。为了能够更改值,我们应定义变量而不是常量。

By definition, constants are immutable. Why would you change the value of a constant in the first place? We use constants whose value is supposed to remain unchanged. To be able to change the value, we would define a variable rather than a constant.

我们已经看到,不可能给已经定义的常量赋予一个新值。但是,存在一种变通方法,可以使用它给常量赋予一个新值。

We have seen that it is not possible to assign a new value to an already defined constant. However, there exists a workaround with which a new value can be assigned to a constant.

该技术使用了 pointers in C 的概念。指针是存储另一个变量地址的变量。因为它是一个变量,所以可以更改其值。而且,此更改会反映在原始变量中。

The technique uses the concept of pointers in C. A Pointer is a variable that stores the address of another variable. Since it is a variable, its value can be changed. Moreover, this change reflects in the original variable.

Example: Change the Value of a Constant

以下代码演示了如何使用指针机制更改常量值 −

The following code demonstrates how to change the value of a constant with the pointer mechanism −

#include <stdio.h>
int main(){
   const int x = 10;
   printf("Initial Value of Constant: %d\n", x);

   // y is a pointer to constant x
   int* y = &x;

   // assign new value
   *y = 100;
   printf("Value of Constant after change: %d", x);
   return 0;
}

执行此代码后,您将获得以下输出 −

On executing this code, you will get the following output −

Initial Value of Constant: 10
Value of Constant after change: 100

请注意,此技术仅对使用 const 限定符定义的 constants 有效。

Note that this technique is effective only for those constants which are defined using the const qualifier.

如果您使用 #define 指令定义了常量,那么您不能应用此流程。这是因为指针具有数据类型,并且必须与要存储其地址的类型相同。另一方面,使用 #define 指令定义的常量实际上没有数据类型。它实际上是在运行时将值替换为宏。

If you have defined your constant using the #define directive, then you cannot apply this process. This is because the pointer has a data type, and it must be of the same type whose address is to be stored. On the other hand, the constant defined using the #define directive doesn’t really have a data type. It is in fact a macro whose value is substituted during the runtime.