Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C / C++ Literals

Tags:

c++

c

Can someone help me to identify in the standards (C99 and C++03) what happens to the line below?

uint16_t a = 5;

So, on the left is the typed variable, on the right is the literal, when and how does the literal value get the type of the variable?

Is the above assignment is equivalent to statement below?

uint16_t a = (uint16_t)5;  /* C */
uint16_t a = reinterpret_cast<uint16_t>(5);  // C++

How about:

uint16_t a = 5u;

Then if you have something like:

uint32_t b = a + 5;

Is the statement above equivalent to statement below?

uint32_t b = (uint32_t)(a + (uint16_t)(5));  /* C */
uint32_t b = reinterpret_cast<uint32_t>(a + reinterpret_cast<uint16_t>(5));  // C++

Do things change in C11 and C++14? Also, please assume that the system int is 32 bit.

I have been coding in C for a while, but never really understood it deeply, but it always bothers me, so I would appreciate if someone can help me to sort it out.

Thank you...

(Edited: added assumption that the int is 32 bit)

like image 237
user1135541 Avatar asked May 26 '15 14:05

user1135541


People also ask

What are the literals in C?

Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal.

How many types of literals are there in C?

There are four types of literals that exist in C programming: Integer literal. Float literal. Character literal.

What are literals examples?

The values assigned to each constant variable are referred to as the literals. Generally, both terms, constants, and literals are used interchangeably. For example, “const int = 5;“, is a constant expression and the value 5 is referred to as a constant integer literal.


1 Answers

The rule is that first the RHS is evaluated, and then the value is converted for the target type. In particular

uint32_t b = a + 5;

is equivalent to

uint32_t b = (uint32_t)((int)a + 5);

If uint16_t is a narrow type, narrower than int.

All operations in C (and I think also in C++) are at least at an integer rank of int.

like image 121
Jens Gustedt Avatar answered Oct 07 '22 22:10

Jens Gustedt