Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use auto keyword to assign a variable of type uint32_t or uint64_t in C++

Tags:

c++11

Consider auto var = 5u;. Here, I am using suffix u, so that var will be deduced as unsigned int. Is there any way to achieve something similar for uint32_t or uint64_t types? Is there any suffix in C++11 or C++14?

like image 288
suresh m Avatar asked Jan 08 '19 16:01

suresh m


2 Answers

I'm assuming you're working with the AAA style suggested by Herb Sutter.

In that case, a nice solution is to simply write:

auto variable_name = uint64_t{ 5000000000 };

This is clear, consistent, and explicitly typed with no nasty C-preprocessor necessary.


Edit: if you want to be absolutely sure when using a literal, an appropriate suffix can be added to the integer literal to ensure great enough range, while still explicitly typing the variable.

like image 164
JMAA Avatar answered Sep 20 '22 14:09

JMAA


You could always define your own suffix

#include <cstdint>
#include <type_traits>

uint32_t operator ""_u32 (unsigned long long v) { return uint32_t (v); } 

int main ()
{
    auto v = 10_u32;

    static_assert (std::is_same <decltype (v), uint32_t>::value);
}
like image 20
nate Avatar answered Sep 21 '22 14:09

nate