假设在if条件(reference)内包含声明是有效的C ++
下面的代码段在编译时带有有关未使用的变量k
(warning: unused variable ‘k’ [-Wunused-variable]
)的警告
#include <iostream>
using std::cout;
using std::endl;
int test (void);
int main (void){
//if((auto k = test()) != 0){
if(auto k = test()){
cout << "odd" << endl;
}
else{
cout << "even" << endl;
}
return 0;
}
int test (void){
static auto invocation_count = -1;
++invocation_count;
return(invocation_count % 2);
}
但是,如果if
条件要用上面的行替换(注释掉),则会发生以下编译错误:
g++ -ggdb -std=c++17 -Wall -Werror=pedantic -Wextra -c code.cpp
code.cpp: In function ‘int main()’:
code.cpp:9:9: error: expected primary-expression before ‘auto’
if((auto k = test()) != 0){
^~~~
code.cpp:9:9: error: expected ‘)’ before ‘auto’
code.cpp:13:5: error: expected ‘)’ before ‘else’
else{
^~~~
code.cpp:17:13: warning: suggest braces around empty body in an ‘if’ statement [-Wempty-body]
return 0;
^
make: *** [makefile:20: code.o] Error 1
两个if
条件语句在技术上不相同吗?为什么一个人编译而另一个人不编译呢?