I'm certainly missing something, but I do not understand why this compiles (with both g++ & clang++):
struct A
{
};
struct B
{
};
int main()
{
A a(B);
}
First of all, B
is a type... not a value. How should I interpret this code?
I'm certainly missing something, but I do not understand why this compiles (with both g++ & clang++):
struct A
{
};
struct B
{
};
int main()
{
A a(B);
}
First of all, B
is a type... not a value. How should I interpret this code?
It's interpreted as the declaration of a function named a
, which takes one argument of type B
and returns A
.
A a{B};
–
Votary void Foo() { void Bar() {printf("Bar!\n");} printf("Foo!\n"); }
... which wouldn't break compatibility simply because code of that form already doesn't compile, and therefore no code like that exists to be broken. Not that I'm willing to actually try to get that into the language, rather I'm just daydreaming :) –
Sunflower It's simply a function declaration declaring a
to be a function returning A
and taking one unnamed parameter of type B
.
It is valid because function declarations as opposed to function definitions are allowed within function definitions.
This issue is known as the most vexing parse. The line A a(B);
can be interpreted as the declaration of a function named a
returning an object of type A
and taking an unnamed parameter of type B
.
One way to avoid this issue is to use the uniform initialization syntax which was introduced in C++11, which consists in using braces instead of parenthesis: A a{B};
returns an error. The line is now interpreted as a variable declaration initialized with B
, which is a type instead of a value.
Here's more information:
struct A { };
are not valid in standard C, even if some compilers allow them. Drop the braces and there wouldn't be a problem there. Also, in C, declaring or defining struct A
does not create a type name A
(you must prefix it with struct
, or add typedef struct A A;
somewhere before A
is used without the struct
prefix). Also in C, there is no alternative parse to the function declaration — using type name(...);
simply cannot ever be a variable definition; it is always a function declaration (or invalid). The code in the question is not valid in C. –
Corrinecorrinne © 2022 - 2024 — McMap. All rights reserved.
A a(B());
which could be a variable definition or function declaration. – Impastostruct A{}; int main() { A(foo); }
compiles as is, even iffoo
doesn't name anything. – Kristof