Confusion in unsigned keyword in C/C++ -
Consider the following two programs. My question is in the first program unsigned
keyword print -12
but I think it should print 4294967284
, but it should be sent to Does not print for% d
Specifiers prints it for % u
specification but if we look at another program, then output is 144
where It should be -112
There is a mess about some code that I can not find. Any help friend!
#include & lt; Stdio.h & gt; Int main () {unsigned int i = -12; Printf ("i =% d \ n", i); Printf ("i =% u \ n", i); Return 0; }
From the top I found this link:
#include & lt; Stdio.h & gt; Int main (zero) {unsigned letter A = 200, b = 200, c; C = A + B; Printf ("result =% d \ n", c); Return 0; }
Each printf
forms the argument specification of something A special type of requirement is "% d"
requires a type of argument int
; "% u"
requires a type of logic unsigned int
. There is full responsibility for passing the right kind of arguments.
unsigned int i = -12;
-12
is of type int
. Initially converts that value from int
to unsigned int
. The converted value (which is positive and very large) is stored in i
if int
and unsigned int
are 32 bits, the accumulated value 42 94967284
(2 32 -12).
printf ("i =% d \ n", i);
i
is the type of unsigned int , but "% d"
is a int
The logic behavior is not defined by the C standard, usually stored in the i
value stored in as in the int
Has been done, will be interpreted. On most systems, the output will be i = -12
- but you should not rely on it.
printf ("i =% u \ n", i);
This will correctly print the value of i
(do not mess with the undefined behavior of the previous statement).
For normal tasks, suppose you say that they are right, the logic often changes into the declared type of parameter, if such a conversion is available. For the variadic function such as printf
, which can argue different numbers and types (arguments), no such conversion can not be done because the compiler does not know the type expected Instead, the logic passes through default argument propaganda , compared to int
, a type of narrowness is encouraged for int
, if Can hold all the values of type int
, or unsigned Int
is otherwise promoted in the float
in double
(This is the reason that "% f"
both Float
and Double
Arguments).
The rule is a narrow unsigned type of argument that often (signed) int
.
Unsigned characters a = 200, b = 200, c;
8-bit bytes, a
and b
are set to 200
.
C = A + B;
is too short to fit into a 400
one unsigned char
. For unsigned arithmetic and conversion, out-of-range results can be reduced in a range of types. c
is set to 144
.
printf ("result =% d \ n", c);
The value of c
is propagated in int
; Although the logic is of an unsigned type, there is enough output to hold all the possible values of type int
result = 144
.
Comments
Post a Comment