Noob question about integer literals and suffixes

First I apologize for my bad english.

When do you use suffixes or why would I use them if I can specify from the beggining the type of the variable or that is a signed or unsigned int

why would I use for example

int x = 75u;

if I can use

unsigned int x = 75;

reference: http://www.cplusplus.com/doc/tutorial/constants/
Last edited on
In such assignments it is mostly useless. But still consider following:
auto x = 75u; //u type is unsigned int

It is useful when you have literal in expression:
1
2
3
4
5
6
7
unsigned shift = 35;

//Incorrect, does not do what you want
unsigned long long mask = 1 << shift; 

//Correct
unsigned long long mask = 1ull << shift; 
Additionally with UDL you may do things with literals you could not before:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//t represents duration of 3 milliseconds
//f represents duration of 100 nanoseconds
auto t = 3ms;
auto f = 100ns;

//Compare with
auto t = std::chrono::seconds(3);

//OK, sleep for 7 second
std::this_thread::sleep_for(5s);

//Not OK, 7 what? seconds, milliseconds, ticks?
std::this_thread::sleep_for(7);

//OK 7 kilometers are not equal to 7 miles
assert(7_km != 7_m);
In most situations, we do not need to use integer-suffixes for our integer literals.

1
2
3
int x = 75u;  // type of 'x' is 'signed int', with or without the suffix on the literal

unsigned int y = -75LL; // type of 'y' is 'unsigned int' 


The tutorial is not precise where it says: "By default, integer literals are of type int".

The type of a decimal integer literal without an integer-suffix is the first of
int, long or long long
in which the value of the literal can be represented.

1
2
3
auto a = 1234 ; // type of 'a' is 'signed int'

auto b = 1234567890123456 ; // type of 'b' is 'long long' (on typical implementations) 


The type of a binary, octal, or hexadecimal integer literal without an integer-suffix is the first of
int, unsigned int, long, unsigned long, long long, unsigned long long
in which the value of the literal can be represented.
Topic archived. No new replies allowed.