Mateusz_madi <> writes:
> I don't know if I understood weel, so if i say:
> int sx = -1;
This initializes sx to -1.
> unsigned ux = -1;
This initializes ux to UINT_MAX, the result of converting -1 from
int to unsigned int.
> and hav a machine using twos complement arithmetic, values goes:
> printf("%o\n", sx) -> 11111111...1111 -> 3FFF...FF
> and
> printf("%o\n", sx)->printf("%o\n", ux) -> 11111111...1111 ->
> 3FFF...FF
>
> Ism't it?
Maybe.
sx is a signed int; "%o" requires an unsigned int. You can pass a
signed int where an unsigned int is expected, or vice versa, *only*
if the value is within the range of representable by both types
(0 .. INT_MAX); otherwise, the behavior is undefined.
In principle, your program (or rather, a complete program that
includes your code fragments) can do literally anything.
In practice, printf will almost certainly interpret the
representation of sx (a signed int) as if it were an object of type
unsigned int, and on a 2's-complement system it will probably behave
as you expect (except that the output will be octal, not hexadecimal
as you've shown).
For example, on my system, this program:
#include <stdio.h>
int main(void)
{
int sx = -1;
unsigned int ux = -1;
printf("ux = %o (undefined behavior) \n", ux);
printf("sx = %o\n", sx);
return 0;
}
produces this output:
ux = 37777777777 (undefined behavior)
sx = 37777777777
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"