困惑关于C宏扩展和整数运算 [英] Confused about C macro expansion and integer arithmetic

查看:148
本文介绍了困惑关于C宏扩展和整数运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  谜语(C语言)

我有几个关于下面的代码片断问题:

I have a couple of questions regarding the following snippet:

#include<stdio.h>

#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};

int main()
{
int d;

for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
printf("%d\n",array[d+1]);

return 0;
}

下面预期的code的输出不打印数组元素。但是,当我加入(INT)元素的宏定义的类型转换为

Here the output of the code does not print the array elements as expected. But when I add a typecast of (int) the the macro definition of ELEMENTS as

 #define TOTAL_ELEMENTS (int) (sizeof(array) / sizeof(array[0]))

它显示了所有的数组元素如预期。

It displays all array elements as expected.


  • 这是如何工作的类型转换?

我有几个问题:


  • 这是否意味着,如果我有一些宏定义为:

  • Does it mean if I have some macro definition as:

的#define AA(-64)

在默认情况下在C,定义为宏所有的常量等同于符号int

by default in C, all constants defined as macros are equivalent to signed int.

如果是的话,


  • 但是,如果我有强行让在宏表现得像一个unsigned int定义的一些常量是有没有恒定的后缀不是我可以使用(我试过UL,UD既不工作)?

  • But if I have to forcibly make some constant defined in a macro behave as an unsigned int is there any constant suffix than I can use (I tried UL, UD neither worked)?

我如何定义宏定义一个恒定表现为unsigned int类型?

How can I define a constant in a macro definition to behave as unsigned int?

推荐答案

看这句话:

for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)

在第一次迭代中,要检查是否

In the first iteration, you are checking whether

-1 <= (TOTAL_ELEMENTS-2)

size_of返回无符号数和校验失败操作(-1 =签署无符号0xFFFFFFFF的在32位机)。

The operator size_of returns unsigned value and the check fails (-1 signed = 0xFFFFFFFF unsigned on 32bit machines).

在循环的简单改变解决了这个问题:

A simple change in the loop fixes the problem:

for(d=0;d <= (TOTAL_ELEMENTS-1);d++)
printf("%d\n",array[d]);

要回答你的其他问题:C宏扩展文本明智,没有类型的概念。 C编译器看到你的循环,因为这:

To answer your other questions: C macros are expanded text-wise, there is no notion of types. The C compiler sees your loop as this:

for(d=-1;d <= ((sizeof(array) / sizeof(array[0]))-2);d++)

如果你想在一个宏来定义一个无符号常量,使用通常的后缀( U 无符号 UL 无符号长)。

If you want to define an unsigned constant in a macro, use the usual suffix (u for unsigned, ul for unsigned long).

这篇关于困惑关于C宏扩展和整数运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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