Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Parsing of types which are described in more than one word

15 views
Skip to first unread message

Paul

unread,
Nov 17, 2018, 5:55:44 AM11/17/18
to
Using a recent version of gcc, the below code (at end of post) doesn't compile.
Presumably, this is because "unsigned int" is interpreted as
"unsigned int int" which, I agree, does not make sense.

It seems to be a precedence problem.
std::cout << ( (unsigned int)(230)); works fine.

Presumably a C++ expert would know that the below code doesn't
compile without needing to try it.
Why does the compiler not recognise unsigned int as the type "unsigned"
in the below context?

Thanks,

Paul


#include<iostream>
int main()
{
std::cout << (unsigned int(230));
}

Bo Persson

unread,
Nov 17, 2018, 1:44:12 PM11/17/18
to
Check the rules for "Explicit type conversion"

https://en.cppreference.com/w/cpp/language/explicit_cast

In particular case 2), which states:

"The functional cast expression consists of a simple type specifier or a
typedef specifier (in other words, a single-word type name: unsigned
int(expression) or int*(expression) are not valid)[...]"


Bo Persson

Alf P. Steinbach

unread,
Nov 17, 2018, 3:20:19 PM11/17/18
to
On 17.11.2018 11:55, Paul wrote:
> Using a recent version of gcc, the below code (at end of post) doesn't compile.
> Presumably, this is because "unsigned int" is interpreted as
> "unsigned int int" which, I agree, does not make sense.
>
> It seems to be a precedence problem.
> std::cout << ( (unsigned int)(230)); works fine.
>
> Presumably a C++ expert would know that the below code doesn't
> compile without needing to try it.
> Why does the compiler not recognise unsigned int as the type "unsigned"
> in the below context?

Because C++ got the botched declaration syntax from C, and use rules
that don't accommodate that syntax.

One might say that the message is, don't use C declaration syntax except
to the degree that it suits C++.

The source code formatting impact of that is:

* One thing declared per declaration.
* Focus on types, with type builders like `*` viewed as basic type
modifiers instead of thing type modifiers: space between type and thing.
* Declarations as close to first use as practically possible.


> #include<iostream>
> int main()
> {
> std::cout << (unsigned int(230));
> }

The simplest remedy is to just omit the word `int`, which is implicit
anyway:

cout << unsigned( V )

Another remedy is to use a C++ named cast:

cout << static_cast<unsigned int>( V )

Or, third remedy, you can define

template< class T > Type_ = T;

... and then write

cout << Type_<unsigned int>( V )

The last approach also lets you use prefix `const` wherever you wish, so
that you can do that /consistently/, which I think is great.


Cheers & hth.,

- Alf
0 new messages