如何最好地在C中使用const关键字? [英] How do I best use the const keyword in C?
问题描述
我试图了解如何在C代码中使用 const
。首先,我并没有真正使用它,但是后来,我看到了很多使用 const
的例子。我应该努力然后回过头来认真地做一些合适的变量 const
吗?还是我会浪费时间?
I am trying to get a sense of how I should use const
in C code. First I didn't really bother using it, but then I saw a quite a few examples of const
being used throughout. Should I make an effort and go back and religiously make suitable variables const
? Or will I just be waisting my time?
我想它可以使人们更容易地阅读预期会改变的变量,特别是在函数调用中,无论是对人类还是对编译器。我是否还缺少其他要点?
I suppose it makes it easier to read which variables that are expected to change, especially in function calls, both for humans and the compiler. Am I missing any other important points?
推荐答案
const
是 typed , #define
宏不是。
const
受C块限制, #define
适用于文件(或更严格地说,是编译单元)。
const
is scoped by C block, #define
applies to a file (or more strictly, a compilation unit).
const
与参数传递最有用。如果您看到带有指针的原型上使用了 const
,则表示传递数组或结构是安全的,因为该函数不会更改它。没有 const
也是可以的。
const
is most useful with parameter passing. If you see const
used on a prototype with pointers, you know it is safe to pass your array or struct because the function will not alter it. No const
and it can.
看一下 strcpy()的定义。
,您会明白我的意思。首先将 const-ness应用于函数原型。改型 const
并不困难,而只是很多工作(但是如果按小时支付,可以。)。
Look at the definition for such as strcpy()
and you will see what I mean. Apply "const-ness" to function prototypes at the outset. Retro-fitting const
is not so much difficult as "a lot of work" (but OK if you get paid by the hour).
还要考虑:
const char *s = "Hello World";
char *s = "Hello World";
这是正确的,为什么?
这篇关于如何最好地在C中使用const关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!