C预处理器 - 示例 [英] C Preprocessor - example

查看:76
本文介绍了C预处理器 - 示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
#define SWAP(a, b, c)(c t; t=a, a=b, b=t)
int main()
{
    int x=10, y=20;
    SWAP(x, y, int);
    printf("%d %d\n", x, y);
    return 0;
}





为什么不允许int声明?我们可以在一个paranthesis中声明吗?是否允许?



why it is not allowing int to be declared?can we declare inside a paranthesis?whether it is allowed?

推荐答案

试试这个



#define SWAP(a,b,c){ct; t = a,a = b,b = t;}



我插入了一个空格,并用圆括号括起来。
Try this instead

#define SWAP(a, b, c) {c t; t=a, a=b, b=t;}

I inserted a space, and exchanged parentheses for braces.


使用 std :: swap [ ^ ]

或者如果您使用预处理器进行此操作:

Use std::swap[^]
or if you''re set on doing this using the preprocessor:
#define SWAP(a,b,c) do {c t=a; a=b; b=t;}while(0)



执行构造确保您可以执行以下操作:


The do while construct ensures that you can do something like this:

if(x < y)
 SWAP(x,y,int);
else
 y++;
// rest of your code



没有不良副作用 - 我建议你使用std :: swap。

< br $>
最好的问候

Espen Harlinn


Without undesired side effects - I would advice you to use std::swap.

Best regards
Espen Harlinn


我不确定你会回答这些问题,但我强烈建议你坚持下去一本体面的C ++书并研究它。尝试使用预处理器宏解决编程问题是一个坏主意,并且可能导致许多难以诊断的问题。使用该语言使用适当的工具和结构编写代码。
I am not sure where you are going with these questions, but I would strongly recommend you get hold of a decent book on C++ and study it. Trying to solve programming problems with preprocessor macros is a bad idea and can lead to many difficult to diagnose problems. Use the language to write your code using the proper tools and constructs.


这篇关于C预处理器 - 示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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