为什么使用#define而不是变量 [英] Why use #define instead of a variable

查看:638
本文介绍了为什么使用#define而不是变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#define 在C ++中有什么意义?我只看到了一些例子,它用于代替一个魔法数,但是我没有看到把这个值赋给一个变量。

What's the point of #define is 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.

推荐答案

这些天大多是风格。当C年轻时,没有一个像const变量这样的东西。所以如果你使用一个变量而不是 #define ,你不能保证某个地方的某个人不会改变它的值,从而在整个程序中造成破坏。

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.

在过去,FORTRAN通过引用向子程序传递偶数常量,并且可能(和头痛诱导)将常量的值更改为2 。有一次,这发生在我正在做的一个程序,唯一的提示,我们有一些错误是我们会得到一个ABEND(异常结束),当程序击中 STOP 999 应该正常结束。

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.

这篇关于为什么使用#define而不是变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆