为什么使用#define而不是变量

发布于 2024-11-06 22:20:56 字数 64 浏览 0 评论 0原文

C++ 中的#define 有何意义?我只看到过使用它来代替“幻数”的示例,但我没有看到仅仅将该值赋予变量的意义。

What is the point of #define in C++? I've only seen examples where it's used in place of a "magic number" but I don't see the point in just giving that value to a variable instead.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

人间☆小暴躁 2024-11-13 22:20:56

#define 是 C 和 C++ 预处理器语言的一部分。当它们在代码中使用时,编译器只需将 #define 语句替换为您想要的内容。例如,如果您厌倦了一直编写 for (int i=0; i<=10; i++) ,您可以执行以下操作:

#define fori10 for (int i=0; i<=10; i++)

// some code...

fori10 {
    // do stuff to i
}

如果您想要更通用的内容,您可以创建预处理器宏:

#define fori(x) for (int i=0; i<=x; i++)
// the x will be replaced by what ever is put into the parenthesis, such as
// 20 here
fori(20) {
    // do more stuff to i
}

如果您只想在某些特定构建中使用某些代码,那么它对于条件编译(#define 的另一个主要用途)也非常有用:

// compile the following if debugging is turned on and defined
#ifdef DEBUG
// some code
#endif

大多数编译器将允许您从命令行(例如g++ -DDEBUG some.cpp),但您也可以在代码中添加一个定义,如下所示:

#define DEBUG

一些资源:

  1. 维基百科文章
  2. C++ 特定站点
  3. GCC 预处理器的文档
  4. 微软参考
  5. C 特定站点 (不过我认为它与 C++ 版本没有什么不同)

The #define is part of the preprocessor language for C and C++. When they're used in code, the compiler just replaces the #define statement with what ever you want. For example, if you're sick of writing for (int i=0; i<=10; i++) all the time, you can do the following:

#define fori10 for (int i=0; i<=10; i++)

// some code...

fori10 {
    // do stuff to i
}

If you want something more generic, you can create preprocessor macros:

#define fori(x) for (int i=0; i<=x; i++)
// the x will be replaced by what ever is put into the parenthesis, such as
// 20 here
fori(20) {
    // do more stuff to i
}

It's also very useful for conditional compilation (the other major use for #define) if you only want certain code used in some particular build:

// compile the following if debugging is turned on and defined
#ifdef DEBUG
// some code
#endif

Most compilers will allow you to define a macro from the command line (e.g. g++ -DDEBUG something.cpp), but you can also just put a define in your code like so:

#define DEBUG

Some resources:

  1. Wikipedia article
  2. C++ specific site
  3. Documentation on GCC's preprocessor
  4. Microsoft reference
  5. C specific site (I don't think it's different from the C++ version though)
吃不饱 2024-11-13 22:20:56

如今主要是风格化的。当 C 还年轻的时候,还没有 const 变量这样的东西。因此,如果您使用变量而不是#define,则无法保证某个地方的某人不会更改它的值,从而对整个程序造成严重破坏。

在过去,FORTRAN 甚至通过引用将常量传递给子例程,并且可以(并且引起头痛)将像“2”这样的常量的值更改为不同的值。有一次,这种情况发生在我正在开发的一个程序中,我们得到的唯一表明出现问题的提示是,当程序遇到 STOP 999 时,我们会得到一个 ABEND(异常结束),即应该可以正常结束。

Mostly stylistic these days. When C was young, there was no such thing as a const variable. So if you used a variable instead of a #define, you had no guarantee that somebody somewhere wouldn't change the value of it, causing havoc throughout your program.

In the old days, FORTRAN passed even constants to subroutines by reference, and it was possible (and headache inducing) to change the value of a constant like '2' to be something different. One time, this happened in a program I was working on, and the only hint we had that something was wrong was we'd get an ABEND (abnormal end) when the program hit the STOP 999 that was supposed to end it normally.

怪我鬧 2024-11-13 22:20:56

有一次我在工作中遇到了麻烦。我被指控在数组声明中使用“幻数”。

像这样:

int Marylyn[256], Ann[1024];

公司政策是避免这些神奇的数字,因为据我解释,这些数字不可移植;它们妨碍了简单的维护。我认为当我阅读代码时,我想确切地知道数组有多大。我输掉了争论,因此,在周五下午,我用 #defines 替换了令人反感的“神奇数字”,如下所示:

 #define TWO_FIFTY_SIX 256
 #define TEN_TWENTY_FOUR 1024

 int Marylyn[TWO_FIFTY_SIX], Ann[TEN_TWENTY_FOUR];

在接下来的周一下午,我被叫来并被指控有被动反抗倾向。

I got in trouble at work one time. I was accused of using "magic numbers" in array declarations.

Like this:

int Marylyn[256], Ann[1024];

The company policy was to avoid these magic numbers because, it was explained to me, that these numbers were not portable; that they impeded easy maintenance. I argued that when I am reading the code, I want to know exactly how big the array is. I lost the argument and so, on a Friday afternoon I replaced the offending "magic numbers" with #defines, like this:

 #define TWO_FIFTY_SIX 256
 #define TEN_TWENTY_FOUR 1024

 int Marylyn[TWO_FIFTY_SIX], Ann[TEN_TWENTY_FOUR];

On the following Monday afternoon I was called in and accused of having passive defiant tendencies.

秋风の叶未落 2024-11-13 22:20:56

#define 可以完成一些普通 C++ 无法完成的工作,例如保护标头和其他任务。但是,它绝对不应该用作幻数 - 应该使用静态常量。

#define can accomplish some jobs that normal C++ cannot, like guarding headers and other tasks. However, it definitely should not be used as a magic number- a static const should be used instead.

迷路的信 2024-11-13 22:20:56

C 过去没有常量,因此#defines 是提供常量值的唯一方法。 C 和 C++ 现在都拥有它们,因此没有必要使用它们,除非要使用 #ifdef/ifndef 测试它们。

C didn't use to have consts, so #defines were the only way of providing constant values. Both C and C++ do have them now, so there is no point in using them, except when they are going to be tested with #ifdef/ifndef.

莫多说 2024-11-13 22:20:56

最常见的用途(除了声明常量之外)是包含保护

Most common use (other than to declare constants) is an include guard.

那请放手 2024-11-13 22:20:56

Define 在编译之前由预处理器评估,而变量在运行时引用。这意味着您可以控制应用程序的构建方式(而不是运行方式)

以下是一些使用无法用变量替换的定义的示例:

  1. #define min(i, j) (((i) < ( j)) ? (i) : (j))
    请注意,这是由预处理器评估的,而不是在运行时计算的

  2. http:// /msdn.microsoft.com/en-us/library/8fskxacy.aspx

Define is evaluated before compilation by the pre-processor, while variables are referenced at run-time. This means you control how your application is built (not how it runs)

Here are a couple examples that use define which cannot be replaced by a variable:

  1. #define min(i, j) (((i) < (j)) ? (i) : (j))
    note this is evaluated by the pre-processor, not during runtime

  2. http://msdn.microsoft.com/en-us/library/8fskxacy.aspx

2024-11-13 22:20:56

#define 允许您在标头中建立一个值,否则该值将编译为大小大于零。您的标头不应编译为大于零的大小。

// File:  MyFile.h

// This header will compile to size-zero.
#define TAX_RATE 0.625

// NO:  static const double TAX_RATE = 0.625;
// NO:  extern const double TAX_RATE;  // WHAT IS THE VALUE?

编辑:正如 Neil 在这篇文章的评论中指出的那样,标头中的显式定义与值适用于 C++,但不适用于 C。

The #define allows you to establish a value in a header that would otherwise compile to size-greater-than-zero. Your headers should not compile to size-greater-than-zero.

// File:  MyFile.h

// This header will compile to size-zero.
#define TAX_RATE 0.625

// NO:  static const double TAX_RATE = 0.625;
// NO:  extern const double TAX_RATE;  // WHAT IS THE VALUE?

EDIT: As Neil points out in the comment to this post, the explicit definition-with-value in the header would work for C++, but not C.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文