简体   繁体   English

在C ++宏“ int val = rand()”中创建新值

[英]Create new value in C++ macro “int val = rand()”

I'm trying to create C++ macro which can do something while condition under "if" is checking. 我正在尝试创建C ++宏,该宏​​可以在“ if”下的条件检查时做些事情。

My macro works in most cases, but I have problem when under if is created temporary value. 我的宏在大多数情况下都可以使用,但是在if被创建为临时值时遇到问题。 Of course I can move creating of new value before "IF", but it is bothersome is I have to do in many places in code. 当然,我可以将创建新值的操作移到“ IF”之前,但这很麻烦,因为我必须在代码中的许多地方进行操作。

It is possible to get work "IF(int val = rand())"? 可以得到工作“ IF(int val = rand())”吗?

This code have no sense, but shows my problem. 这段代码没有意义,但是显示了我的问题。

#include <iostream>
#include <cstdlib>
#include <ctime>

bool printIf(int line, bool val)
{
  std::cout << "Line: " << line << std::endl;
  return val;
}

#define IF(x) if( (x) ? printIf(__LINE__, true) : printIf(__LINE__, false) )

int main()
{
  srand(time(NULL));
  //int val;
  //IF (val = rand())
  IF(int val = rand())
  {
    std::cout << "val = " << val << std::endl;
  }
}

Errors while compilation: 编译时出错:

$ g++ main.cpp && ./a.out
main.cpp: In function ‘int main()’:
main.cpp:18:6: error: expected primary-expression before ‘int’
   IF(int val = rand())
      ^
main.cpp:11:20: note: in definition of macro ‘IF’
 #define IF(x) if( (x) ? printIf(__LINE__, true) : printIf(__LINE__, false) )
                    ^
main.cpp:18:6: error: expected ‘)’ before ‘int’
   IF(int val = rand())
      ^
main.cpp:11:20: note: in definition of macro ‘IF’
 #define IF(x) if( (x) ? printIf(__LINE__, true) : printIf(__LINE__, false) )
                    ^
main.cpp:22:1: error: expected ‘)’ before ‘}’ token
 }
 ^
main.cpp:22:1: error: expected primary-expression before ‘}’ token

I belive the problem is that you are wrapping the variable decleration in () . 我相信问题是您将变量decleration包装在() If I remove the parentheses then the code compiles: 如果删除括号,则代码将编译:

#include <iostream>
#include <cstdlib>
#include <ctime>

bool printIf(int line, bool val)
{
  std::cout << "Line: " << line << std::endl;
  return val;
}

#define IF(x) if( x ? printIf(__LINE__, true) : printIf(__LINE__, false) )

int main()
{
  srand(time(NULL));
  //int val;
  //IF (val = rand())
  IF(int val = rand())
  {
    std::cout << "val = " << val << std::endl;
  }
}

Output: 输出:

Line: 18
val = 1

Live Example 现场例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM