是一个定义数组的长度与宏"优良的实践与QUOT ;? [英] Is defining the length of an array with a macro "excellent practice"?

查看:125
本文介绍了是一个定义数组的长度与宏"优良的实践与QUOT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过了一本书叫 C语言程序设计工作:一种现代方法,并在首节讨论阵列,笔者指出:


  使用宏定义数组的长度

出色的做法


然后使用简单的例子:

 的#define N 10
...
诠释一个[N];

据我所知,它是与能返回到程序的源代码code和改变的价值,并使其成为一个宏,也许更容易为程序员,但我不某些。 为什么这是一个很好的做法,或者是目标?


解决方案

这是一个很好的做法,因为


  • 数组的大小显然是硬codeD

  • ,但它不应该有直接注入源$ C ​​$ C
  • 一个神奇的数字
  • 因此,宏是给它一个可读的名称,从源头上取下一个好办法

话虽这么说,我不知道我同意这是最好的办法。枚举也适用,避免一些问题与宏(例如难以覆盖,静静编译)。和IIRC一个 const int的工作为好。

有关这个参考使用编译 CC

  const int的S = 1;
诠释一个[S]。
诠释主(){
返回0;
}


  

苹果LLVM 4.2版(铛-425.0.28)(基于LLVM 3.2svn)结果
  目标:x86_64的 - 苹果darwin12.4.0结果
  线程模型:POSIX


I'm working through a book called C Programming: A Modern Approach and in the first section discussing arrays, the author states:

using a macro to define the length of an array is excellent practice

Then uses the brief example:

#define N 10
...
int a[N];

I understand that it has something to do with being able to go back into the source code of the program and change the value, and making it a macro maybe makes it easier for the programmer, but I'm not certain. Why is this an excellent practice, or is it objective?

解决方案

It's a good practice because

  • the array size obviously has to be hard-coded
  • but it shouldn't have a magic number injected directly into the source code
  • therefore, a macro is a good way to give it a readable name and remove it from the source

That being said I'm not sure I agree this is the best way. An enum also works and avoids some of the problems with macros (e.g. harder to overwrite and silently compile). And IIRC a const int works as well.

For reference this compiles with cc:

const int s = 1;
int a[s];


int main() {
return 0;
}

Apple LLVM version 4.2 (clang-425.0.28) (based on LLVM 3.2svn)
Target: x86_64-apple-darwin12.4.0
Thread model: posix

这篇关于是一个定义数组的长度与宏"优良的实践与QUOT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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