G
Glen Herrmannsfeldt
Mark Gordon said:I think that Dan's point is that 6 weeks later someone else calls that
function (or does some other change) without realising that you expect
a short.
It doesn't. The following are the same as far as ISO C is concerned.
short i = va_arg(ap,int);
short i = (short)va_arg(ap,int);
No, I meant int i=(short) va_arg(ap,int);
According to P197 of K&R2, "When any integer is converted to a signed
tpe, the value is unchanged if it can be represented in the new type and
is implementation defined otherwise".
So casting or assigned an integer to a short is not guaranteed to
enforce the range, and if the implementation documented that on
accessing the short you might get the original int value (say because it
is stored in a register and has not been truncated) then I would assume
it would still be conforming and your use of it as an array index could
then invoke undefined behaviour.
That was the question I was ask, whether the compiler would enforce the
cast. It seems, then, that it doesn't, which is the answer to the question
I was trying, not very successfully, to ask.
No, I mean something like int i=va_arg(ap,int) & 0x7fff; /* assume I want
16 bit signed short */
(snip)
If, on the other hand, you use unsigned short the result is defined by
the standard, but it is unlikely to be what you want.
IMHO you should write code to check the value yourself if you really
want a short when it is being passed as part of a varidac parameter.
Either that or accept that out of range values will invoke incorrect
behaviour (depending on your use you may not invoke UB).
Yes, that is probably the best way. I was asking if the other way would
work, and apparently it doesn't.
In that case you may well find that short and double are identical.
So it also doesn't enforce casts to (float).
It does not have to.
That is what I was asking.
IIRC when casting from double to float it has to do the cast to enforce
the correct precision, but it still does not have to do what you expect
for out of range values.
No, I was only asking about the precision question for the float/double cast
question.
No, the question was for a cast, applied to the result of the va_arg() call.
If you are assigning to a short it makes not difference.
If the value is converted to a short (either by cast or due to
assignment) and it is out of range you invoke implementation defined
behaviour which I would expect to not be what you want.
Well, I might use it in a subscript for an array dimensioned USHORT_MAX, and
cast to (unsigned short) in attempt to force the subscript to be within
range. There are other ways to do it, and it seems like this way doesn't
work. That is all that I was asking, not for a long discussion. Well, the
original question was answered a long time ago, but this new question was
not.
-- glen