Create new value in C++ macro "int val = rand()" -
i'm trying create c++ macro can while condition under "if" checking.
my macro works in cases, have problem when under if created temporary value. of course can move creating of new value before "if", bothersome have in many places in code.
it possible work "if(int val = rand())"?
this code have no sense, shows 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 problem wrapping variable decleration in ()
. if remove parentheses 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
Comments
Post a Comment