Assume it is valid C++ to include declaration inside the if condition (reference)
The following code segment compiles with a warning about the unused variable 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);
}
But if the if
condition is to be substituted by the line above (commented out), the following compilation errors ensue:
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
Aren't the two if
condition statements technically the same? Why is it that one compiles where as the other doesn't?
Aucun commentaire:
Enregistrer un commentaire