Is this code valid

E

Emmanuel Delahaye

In said:
I think the code is valid but it is not portable. It's a typical case
of byte swapping and you see different results on Solaris and Linux
boxes.

Here are my results on solaris and linux:

solaris: 3F B9 99 99 99 99 99 9A
linux: 9A 99 99 99 99 99 B9 3F

if you are running your code on a single platform and not worrying
about taking it to other platforms then you can carry on with you
code.

The code *is* portable. The result is not.
 
O

Orhan Kavrakoglu

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?
 
M

Martin Dickopp

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
 
V

Vittal

Thanks for your correction.. Btw,I meant results will be different on
different machine...hence said not portable
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,143
Messages
2,570,821
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top