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

查看:14
本文介绍了对 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
",array[d+1]);

return 0;
}

这里的代码输出没有按预期打印数组元素.但是当我添加 (int) 的类型转换时,ELEMENTS 的宏定义为

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.

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

基于此,我有几个问题:

Based on this I have few questions:

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

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

#define AA (-64)

在 C 中默认情况下,所有定义为宏的常量都等价于 signed 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
",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 表示 unsignedul 表示 无符号长).

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天全站免登陆