Defining fstream inside a 'if' conditional

2019-04-21 03:09发布

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: '('

2条回答
在下西门庆
2楼-- · 2019-04-21 03:38

The code you have is not legal.. yet. Prior to C++11 a if statement could be

if(condition)
if(type name = initializer)

and name would be evaluated as a bool to determine the condition. In C++11/14 the rules expended to allow

if(condition)
if(type name = initializer)
if(type name{initializer})

Where, again, name is evaluted as a bool 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.

if (std::ifstream input("input_file.txt"); input.is_open())
{
    // do stuff with input
}
else
{
    // do other stuff with input
}

It should be noted though that this is just syntactic sugar and the above code is actually translated to

{
    std::ifstream input("input_file.txt")
    if (input.is_open())
    {
        // do stuff with input
    }
    else
    {
        // do other stuff with input
    }
}
查看更多
SAY GOODBYE
3楼-- · 2019-04-21 03:55

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:

if (std::ifstream input{"input_file.txt"})
    ;
查看更多
登录 后发表回答