Reputation: 1891
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)
Upvotes: 15
Views: 1076
Reputation: 78903
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
.
Upvotes: 6