https://www.sharetechnote.com/html/C_const.html
你是一个经验丰富的中英文翻译,对我说的话进行中英文互译。你只需要简洁的给我翻译。即使你说的是一个词,你也要翻译。我说的是"const"关键字与变量一起使用。它使变量成为常量值。这意味着用const关键字声明的变量在之后不能被更改。实际上,这个语句’它使变量成为常量值’让很多人感到困惑。当我们说’变量’时,意味着它可以随时更改,但是用const关键字声明的变量不能被更改。这对许多人来说可能很困惑。
我理解这可能让人感到困惑,但就把它当作是这样的。这就是它的实现方式。
Example 01 >
Let's take a look at a simple example showing the implication of 'const' keyword.
void main ()
{
int a = 0;
int b = 0;
a = b;
b = a;
}
void main ()
{
int a = 0;
const int b = 0; // this means this integer type variable called 'b' should not (will not) changed.
a = b;
b = a; // this line gives an error '[Error] assignment of read-only variable 'b'
// this is because you tried to change a value for a 'const variable'.
}
Example 02 >```
好的,我会尽量简洁地为你翻译。
假设我们有一个值类型变量,那么'const'的行为是非常直接的。然而,如果'const'与指针类型一起使用(例如char *),情况就会变得复杂许多。让我们看看下面的例子。这是C库中著名的strcpy函数。如你所见,_Dest被定义为'char *',而_Source被定义为'const char *'。这意味着在strcpy()函数内,_Dest的值会被改变,但_Source的值不会改变。考虑到strcpy()的功能,这是有意义的。
```c
char * __cdecl strcpy(char * __restrict__ _Dest,const char * __restrict__ _Source);
现在让我们看下面的例子,看看它是如何工作的。
#include<stdio.h>
#include <string.h>
int main()
{
char dest1[255];
const char dest2[255];
//const char dest2[255] = "Any String Here";
//const char *dest2 = "Any String Here";
char src1[] = "source 2";
const char *src2 = "source 1";
strcpy(dest1,src1);
printf("dest1 = %s\n",dest1);
strcpy(dest1,src2);
printf("dest1 = %s\n",dest1);
printf("dest2 = %s\n",dest2);
// you would see Compiler Warning as shown below.
strcpy(dest2,src1); // [Warning] passing argument 1 of 'strcpy' discards 'const' qualifier from pointer target type
printf("dest2 = %s\n",dest2);
strcpy(dest2,src2); // [Warning] passing argument 1 of 'strcpy' discards 'const' qualifier from pointer target type
printf("dest2 = %s\n",dest2);
return 0;
}
Example 03 >
Let's create a function in two different way as shown below and see what happens.
// cAry here is defined without 'const'.
void toUpper(char cAry[255],int n)
{
int i = 0;
for( i = 0; i <n; i++)
{
if(cAry[i]=='\0') break;
cAry[i] = toupper(cAry[i]); // the contents of cAry[] is being changed here.
// no problem in this case.
}
}
// cAry here is defined with 'const'.
void toUpper(const char cAry[255],int n)
{
int i = 0;
for( i = 0; i <n; i++)
{
if(cAry[i]=='\0') break;
cAry[i] = toupper(cAry[i]); // the contents of cAry[] is being changed here.
// you would see complier error as follows.
// [Error] assignment of read-only location '*(cAry + (sizetype)...
}
}