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