Orhan Kavrakoglu said:
In said:
Is the code below that gives the bytes that make up a double valid?
/******/
#include <stdio.h>
int
main(void)
{
double w=0.1;
unsigned char *p;
unsigned char c;
size_t i;
p=(unsigned char *)&w;
for(i=0;i < sizeof w;i++,p++)
{
c=*p;
printf("%X ",(unsigned) c);
}
getchar();
return 0;
}
/****/
[snip]
3. c is cast to unsigned in the printf call, to match the type expected
by %X.
Why is this necessary?
The following text in the standard requires it for a program with
well-defined behavior:
| 7.1.4 Use of library functions
|
| 1 Each of the following statements applies unless explicitly stated
| otherwise in the detailed descriptions that follow: If an argument
| to a function has an invalid value (such as a value outside the
| domain of the function, or a pointer outside the address space of
| the program, or a null pointer, or a pointer to non-modifiable
| storage when the corresponding parameter is not const-qualified) or
| a type (after promotion) not expected by a function with variable
| number of arguments, the behavior is undefined. [...]
Since `c' has type `unsigned char', it is promoted to `int', unless
`int' cannot represent all values of `unsigned char', in which case `c'
is promoted to `unsigned int'. To make the program work correctly on
all implementations (even those which can represent all values of an
`unsigned char' in an `int', which is commonly the case for hosted
implementations), the cast is therefore necessary.
Martin