Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: '('
like image 798
user3358771 Avatar asked Apr 04 '17 19:04

user3358771


1 Answers

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
    }
}
like image 132
NathanOliver Avatar answered Sep 28 '22 09:09

NathanOliver