Search code examples
c++if-statementfstreamifstreamofstream

Defining fstream inside a 'if' conditional


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

Solution

  • 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
        }
    }