1

During dubugging some newbie's code, I found very weird declaration in c++ that actually defines the variable. Consider the following program:

#include <iostream>

struct Foo {
    int number;
};

int main(void) {
    Foo(Bar);
    std::cout<<Bar.number<<std::endl;
}

Running the program outputs some random integer. Of course, that's because number is not initialized.

But that not the problem. The problem is that above program compiles without a single warning, and Bar is interpreted as variable of class Foo. That means Foo(Bar) is equivalent to Foo Bar! I have not seen any declartion syntax like this before in c++. And cppreference is not being helpful. Anyone can instruct me whether this is a valid declaration in c++ standard, or is just a weird bug involving some kind of most vexing parse?

The program compiled on g++ 5.4.0, on Ubuntu 16.04.

he rambled
  • 154
  • 2
  • 8
  • 3
    Parentheses are allowed in variables and types declarations. They are very useful in declaration that contain complex types. E.g. `Foo (*Bar)()` -- `Bar` is a pointer to a function that returns an object of type `Foo`. `Foo(Bar)` is syntactically correct and equivalent to `Foo Bar`. It is not recommended because it is misleading, resembling the declaration of a function. – axiac Jun 06 '18 at 09:11
  • @axiac Thank you for the helpful sementic explanation. – he rambled Jun 06 '18 at 09:12

0 Answers0