I recently came across this construct:
int(m);
which seems to be equivalent to:
int m;
Oddly, I have never seen this particular idiom before. Can someone point me to a reference where I can read the spec on this, or just explain directly? Does this also work in straight C?
Thanks,
ConfusedDeveloper
It is not an "idiom". It is just a redundant pair of parentheses. Grammatically, they can be there, but they serve no purpose.
Sometimes similar seemingly superfluous parentheses can be used to resolve ambiguity in C++ declarations, like
int a(int());
which declares a function can be turned into
int a((int()));
which is equivalent to
int a = int();
and defines a variable. But this is not exactly what you have in your case.
It's also used to cast. Like,
double m= 10.0;
int n= int(m);
In addition to other answers, sometimes declarator has to be parenthesized.
For example:
struct A {};
struct B { A a; };
namespace N {
struct B { int a; };
void f()
{
A (::B::*p) = &::B::a; // this () cannot be omitted
}
}
If ()
is omitted in the above code, compiler recognizes a consecutive nested
name specifier A::B
instead of A
and ::B
, and will issue an error.
This parenthesis is necessary, but sometimes leads to a misleading situation.
struct A {
int m;
A() {}
A( int ) {} // this isn't called
};
int i;
int main()
{
A(i); // this is a declaration
i.m = 1; // ok
}
In the above code, A(i)
is a declaration(and also a definition in this case) of an object i
,
instead of a constructor call expression with an int
argument i
.
Hope this helps.