Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any need to make an integer literal unsigned?

Tags:

c++

I see lots of code doing things like,

static constexpr std::size_t value = 1024u;

I understand that u is specifying 1024 as an unsigned integer, but why bother with marking as unsigned?

like image 370
ronald_s56 Avatar asked Dec 12 '18 15:12

ronald_s56


People also ask

Which are unsigned int literals?

There are no negative integer literals. Expressions such as -1 apply the unary minus operator to the value represented by the literal, which may involve implicit type conversions. In C prior to C99 (but not in C++), unsuffixed decimal values that do not fit in long int are allowed to have the type unsigned long int.

What is a valid integer literal?

An integer has no fractional part and cannot include a decimal point. Built-in data types of SQL that can be exactly represented as literal integers include BIGINT, BIGSERIAL, DECIMAL(p, 0), INT, INT8, SERIAL, SERIAL8, and SMALLINT.

Are Hex literals unsigned?

A hexadecimal value is int as long as the value fits into int and for larger values it is unsigned , then long , then unsigned long etc.

What is an integer literal in Python?

In computer science, an integer literal is a kind of literal for an integer whose value is directly represented in source code.


1 Answers

There is no point at all in writing u in your case as the compiler will make the conceptual conversion. It's a bad habit to get into insfar that it can introduce portability issues.

It is occasionally necessary though: std::accumulate is an important example - the type of the initial value is the type of the result.

If you were to use auto then you'll see that the rules become quite involved. For example, if you use a hexadecimal literal then the unsigned types become candidates.

Reference: https://en.cppreference.com/w/cpp/language/integer_literal

like image 158
Bathsheba Avatar answered Oct 06 '22 23:10

Bathsheba