sizeof
expects either a value (an expression) or a type. (int)
is neither one of them - you can't treat types as values and expect them to act correctly in cases where you would expect values to do so, because they are not (first-class) values. Therefore, you can't just parenthesize a type and have the same type come out.
"error: expected expression" when using extra parentheses
-
01-06-2022 - |
Question
I just stumbled across a compiler error that I was not expecting:
std::cout << sizeof(int) << std::endl; // ---> this is valid (obviously)
std::cout << sizeof((int)) << std::endl; // ---> this leads to
// "error: expected expression"
Similarly, we have:
template <typename T>
struct Foo
{
T value;
};
Foo<int> f1; // ---> this is valid (obviously)
Foo<(int)> f2; // ---> this leads to "error: expected expression"
Apparently, the compiler interprets (T)
as an explicit conversion and stops there. I understand the error, I understand what the compiler is expecting, what I do not get is why (T)
cannot be treated as T
if it is not in the context of (T)(exp)
. I thought that the compiler would be able to see through that (and probably return a warning), so I suppose this means that there are ambiguous cases where allowing those extra parentheses would lead to errors.
My questions are: when would that be dangerous? Is that in the C++ standard?
This was tested with clang 3.3. and g++ 4.7.2.
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow