0
How will this code function and what is its output....
#include <iostream> int main(int argc, char **argv) { std::cout << 25u - 50; return 0; }
3 Respostas
+ 2
25u the value 25 is an unsigned int
25l (lowercase L) 25 is a signed long
25L ditto
25uL unsigned long
25LL a signed long long
25uLL unsigned long long
And on a 16-bit machine where int is 16bits, this expression will result in a negative value:
long x = 30000 + 30000;
Both 30000 literals are int, and since both operands are int, the result will be int. A 16-bit signed int can only contain values up 32767, so it will overflow. X will get a strange, negative value because of this, rather than 60000 as expected.
The code
long x =30000u + 30000u;
Will however behave as expected
+ 1
25 unsigned cant go negative so you get the largest value for an int possible minus 25
0
In C++, if the types of two operands differ from one another, then the operand with the “lower type” will be promoted to the type of the “higher type” operand, using the following type hierarchy : long double, double, float, unsigned long int, long int, unsigned int, int (lowest).
So when the two operands are, 25u (unsigned int) and 50(int), the 50 is promoted to also being an unsigned integer (i.e., 50u).
Moreover, the result of the operation will be of the type of the operands. Therefore, the result of 25u - 50u will itself be an unsigned integer as well. So the result of -25 converts to 4294967271 when promoted to being an unsigned integer