C ++:宏参数中可以有空格吗? [英] C++: Can a macro argument have a space in it?

查看:96
本文介绍了C ++:宏参数中可以有空格吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我定义一个接受参数的宏,如下所示.

If I define a macro taking argument as below.

#define define_int(a) int a;

并在参数之间提供空格,如下所示

And provide an argument with space in between like below

define_int(* a)

并获得输出?

int * a;


预期用途


Intended use

#define ASSIGN(A,B) B=A;

我想直接使用此宏作为函数从函数中返回

I want to return from a function directly using this macro as

ASSIGN(A, return B)

以便输出,

return B = A;

推荐答案

空间本身不执行任何操作,因为空间用于分隔预处理器令牌,并且宏在此之后进行了预处理.因此,您可以根据需要添加任意多个空格.

The space itself does nothing, since spaces are used to separate pre-processor tokens and the macro is pre-processed after that's done. So you can add as many spaces as you like.

唯一的问题是您不能违反语法,因此不会编译此经典错误:

The only issue is that you can't violate the syntax, so this classic mistake won't compile:

#define A (B, C) ...  // bad syntax, space between macro name and parameter list

#define A(B, C) ... // ok

是的,您可以写一些晦涩的东西

So yes you can write something obscure like

#define define_int(a) int a;
...
define_int(*const a);

define_int(*        const     a     );

并获得类型 int * const a; .

为什么您要编写如此可怕的代码,我不知道.用C发明自己的秘密宏语言是其中的一项愚蠢的事情.

Why you would ever want to write such horrible code, I have no idea. Inventing your own secret macro language in C is one of them royally stupid things.

关于发明诸如 ASSIGN(A,return B)之类的东西以从函数宏中返回并带有一些清理代码的编辑,这种宏的不同形式既常用又幼稚.

Regarding the edit of inventing something like ASSIGN(A, return B) for a return from function macro with some clean-up code, different flavours of such macros are both commonly-used and naive.

当您需要从多个地方返回时,在函数中集中进行清理的正确方法是(伪代码):

The proper way to centralize clean-up in a function when you need to return from multiple places is this (pseudo code):

void wrapper (void)
{
  something a = allocate_stuff();
  error result = the_actual_function(a);

  if(result == whatever)
    do_that();

  cleanup(a);
}

inline error the_actual_function (something a)
{
  ...
  if(bad)
  {
    return error_42;
  }
}

当您只需要返回错误时,此设计模式可减少实际功能内部的混乱情况.它也摆脱了错误goto的"BASIC风格",这是编写错误处理程序的另一种相当幼稚的方式.

This design pattern reduces clutter inside the actual function, when you only need to return upon error. It also gets rid of "BASIC style" on error goto, which is another rather naive way of writing error handlers.

这篇关于C ++:宏参数中可以有空格吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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