Casting return value to fit within constraints of error values (portability)

C

clayne

I realize this may work for the majority of platforms. But I am
concerned about the aspects of sign extension and portability.

Is this portable:

{
unsigned long bw;
[...]

if ((signed long)(bw = read(s, buf, sizeof(buf))) == -1) {
error_handling();
}
}

With the goal being able to utilize larger unsigned values but still
being able to check for a return value of "-1" (since this is the
mechanism read() uses) to handle errors?
 
C

clayne

clayne said:
unsigned long bw;
[...]

if ((signed long)(bw = read(s, buf, sizeof(buf))) == -1) {

In retrospect this is probably a pointless "workaround" as read() won't
ever be returning more than signed size_t (ssize_t) in the first place,
so no need to declare 'bw' as unsigned long or size_t, etc.
 
C

clayne

clayne said:
In retrospect this is probably a pointless "workaround" as read() won't
ever be returning more than signed size_t (ssize_t) in the first place,

Interesting though that I already see (Solaris for instance):

ssize_t read(int fildes, void *buf, size_t nbyte);

The read() function attempts to read nbyte bytes from the
file associated with the open file descriptor, fildes, into
the buffer pointed to by buf.
 
M

Mark McIntyre

ssize_t read(int fildes, void *buf, size_t nbyte);

you /are/ aware that read() is offtopic here? Its a posix function,
probably best discussed in a unix group.
Mark McIntyre
 
J

Jack Klein

comp.lang.c:

I wonder whether it is worth replying, since you have done a
commendable job of replying to yourself.

And just for the heck of it, I will point out that there is no "read"
function in C, it is a POSIX extension and hence off-topic here. But
your underlying problem is similar to one that could happen when you
call time(), which could return (time_t)-1.
I realize this may work for the majority of platforms. But I am
concerned about the aspects of sign extension and portability.

Is this portable:

{
unsigned long bw;
[...]

if ((signed long)(bw = read(s, buf, sizeof(buf))) == -1) {

Why, oh why, would you want to do this?
error_handling();
}
}

With the goal being able to utilize larger unsigned values but still
being able to check for a return value of "-1" (since this is the
mechanism read() uses) to handle errors?

Let's replace read with time(), to keep it topical.

#include <time.h>

void func(void)
{
time_t now;
if ((now = time(NULL)) == (time_t)-1)
{
/* error handling */
}
}

Don't case the returned value to another type, cast the comparison
value constant to the type of the return value.
 

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

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top