一些错误输出使用C中的宏 [英] some error in output in using macro in C

查看:84
本文介绍了一些错误输出使用C中的宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的code是: -

my code is:-

#include<stdio.h>
#include<conio.h>

#define sq(x) x*x*x

  void main()
  {
    printf("Cube is : %d.",sq(6+5));
    getch();
  }

输出是: -

The output is:-

Cube is : 71.

现在请大家帮我出为什么输出是71,而不是1331 ...

now please help me out that why the output is 71 and not 1331...

感谢您提前。

推荐答案

您需要周围的括号参数

#define sq(x) ((x)*(x)*(x))

如果没有括号,前pression将扩大到:

Without the parentheses, the expression will expand to:

6+5*6+5*6+5

你可以看到为什么它会评估为 71

一个更安全的解决方案是使用内联函数。但是,你需要定义一个不同的每种类型。这也可能是更清晰重命名宏。

A safer solution would be to use an inline function instead. But, you would need to define a different one for each type. It might also be more clear to rename the macro.

static inline int cube_int (int x) { return x*x*x; }

这篇关于一些错误输出使用C中的宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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