1

The following code is rejected by both clang and gcc but accepted by msvc:

#include <iostream>

int main() 
{
    std::cout << unsigned long long(10);
}

The error is

error: expected primary-expression before 'unsigned'

godbolt

This should compile, right?

Timo
  • 9,269
  • 2
  • 28
  • 58
  • 3
    I am pretty sure you have to use parentheses around the c-style cast, as in ```std::cout << (unsigned long long)(10);```, or better practice to just use c++-style cast of ```std::cout << static_cast(10);``` – Nikhil Chatterjee Oct 20 '20 at 16:43
  • @NikhilChatterjee I've tried parens around the whole expression and that didn't work so I thought it can't be parens, lol – Timo Oct 20 '20 at 16:46
  • 1
    @Timo You would need parenthesis around the *type*, not the *whole expression* (though, that is not a bad idea, either, when using C-style casting). – Remy Lebeau Oct 20 '20 at 16:51
  • @RemyLebeau yeah I've read your answer, thank you :D – Timo Oct 20 '20 at 16:51

1 Answers1

8

No, what you have shown should NOT compile. See Explicit type conversions on cppreference.com for details.

In a function-style cast, spaces are not allowed in the type name. For such types, you would need to use a C-style or C++-style cast instead, eg:

std::cout << ((unsigned long long)10);
or
std::cout << static_cast<unsigned long long>(10);

Otherwise, use a type alias instead, eg:

using ull = unsigned long long; // C++11 and later
or
typedef unsigned long long ull; // pre-C++11

std::cout << ull(10);

Note, the <cstdint> header may have a uint64_t type you can use, eg:

#include <cstdint>

std::cout << uint64_t(10);
or
std::cout << ((uint64_t)10);
or
std::cout << static_cast<uint64_t>(10);

That being said, for integer literals, you can alternatively use the ULL suffix (C++11 and later), eg:

std::cout << 10ULL;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Hmm but variable declarations are ok. `unsigned long long (x);`. Why is casting different? Is there a parsing problem or is this just because? – Timo Oct 20 '20 at 16:49
  • 2
    @Timo in a variable declaration, `unsigned long long (x);` is treated the same as `unsigned long long x;`, all parenthesis around the variable name are ignored, so even something like `unsigned long long ((((x))));` is a valid declaration of `x`. See [Why does C++ allow us to surround the variable name in parentheses when declaring a variable?](https://stackoverflow.com/questions/29675601/) – Remy Lebeau Oct 20 '20 at 16:57