In an answer there was the following code:
if (std::ifstream input("input_file.txt"))
;
Which seems convenient, limiting the scope of the 'input' variable to where it's confirmed to be valid, however neither VS2015 nor g++ seems to compile it. Is it some compiler specific thing or does it require some extra flags?
In VS2015 the IDE highlights "std::ifstream" and the "input_file.txt" as well as the last parentheses. "std::ifstream" is flagged with "Error: a function type is not allowed here".
VS2015 C++ compiler gives following errors:
- C4430 missing type specifier - int assumed. Note: C++ does not support default-int
- C2059 syntax error: '('
The code you have is not legal.. yet. Prior to C++11 a if statement could be
and
name
would be evaluated as abool
to determine the condition. In C++11/14 the rules expended to allowWhere, again,
name
is evaluted as abool
after it is initialized to determine the condition.Starting in C++17 though you will be able to declare a variable in a if statement as a compound statement like a for loop which allows you to initialize the variable with parentheses.
It should be noted though that this is just syntactic sugar and the above code is actually translated to
According to http://en.cppreference.com/w/cpp/language/if that code is not legal (This site is pretty reputable but I can hunt for the standard reference if desired). You can declare variables in an if condition but they must be initialized by
=
or{}
. So assuming you have at least C++11 you can do: