about 5 years ago

什麼時候用 #define 什麼時候用 const?

一般來說推薦 C 用 #define,C++ 用 const

原本能盡量用 const 就用 const

但在 C 裡面,const 並不是 常數(constant) !他真正的意義是 唯讀(read only)

所以如果有一段 C 的程式:

#include <stdio.h>
const int ARRAY_SIZE = 100;
int data[ARRAY_SIZE];
int main(void){

error: variably modified 'data' at file scope
這是因為 compiler 在 file scope 並不允許非常數的 array 宣告(ps. block scope 就沒這問題)

所以才有人建議在 C 就用 #define,C++ 則盡量用 const

但是 #define 也有自己的問題,像是:

  1. 不加雙括號會造成無法預期的計算(這很常見)
  2. 因為 code 已經被 pre-processor 轉換成數字了,compiler 的錯誤訊息就不會告訴你是哪個變數,在 debug 上比較不方便

除了 #define 也可以用 enum
enum { array_size = 100 };
但缺點就是只限於 int 型別

pointer reading trick

Q: int const vs. const int?

Ates Goral:

The trick is to read the declaration backwards (right-to-left):

const int a = 1; // read as "a is an integer which is constant"
int const a = 1; // read as "a is a constant integer"

Both are the same thing. Therefore:

a = 2; // Can't do because a is constant

The reading backwards trick especially comes in handy when you're dealing with more complex declarations such as:

const char *s;      // read as "s is a pointer to a char that is constant"
char c;
char *const t = &c; // read as "t is a constant pointer to a char"

*s = 'A'; // Can't do because the char is constant
s++;      // Can do because the pointer isn't constant
*t = 'A'; // Can do because the char isn't constant
t++;      // Can't do because the pointer is constant

Pat Notz:

To keep things straight, I always use the convection "put const on the outside"
where by "outside" I mean the far left or far right.
That way there is no confusion -- the const applies to the closest thing (either the type or the *).

← LOGDOWN 推廣文 大家都知道全球經濟體制會崩壞,然後呢 →
comments powered by Disqus