Re: string operation??



Spiros Bousbouras wrote:
Christopher Benson-Manica wrote:
mark_bluemel@xxxxxxxxx wrote:

char str[10]="string";
str[0]^=str[1];

Now to the question. In "str[0]^=str[1]" you are not operating on a
string, but on a character in that string. We are doing an exclusive
bitwise or operation with the first two characters and storing the
result in the first. Why the code is doing that is beyond me, though
I'd suspect it was a crude cryptographic technique....

Is it implementation-defined whether the above code yields undefined
behavior or not? (If char is signed, may str[0]^=str[1] not generate
a trap representation?)

Probably not. Footnote 44 on page 38 of N1124 says

Some combinations of padding bits might
generate trap representations, for example,
if one padding bit is a parity bit. Regardless,
no arithmetic operation on valid values can
generate a trap representation other than as
part of an exceptional condition such as an
overflow, and this cannot occur with unsigned
types.

I'm not completely certain that bitwise operators count
as arithmetic operators but they should be.

They are, however this footnote only addresses trap representations as
a result of padding bits, which makes sense since it is attached to a
description of unsigned types. Signed types have another possibility
for a trap representation.

Plus it
feels that char1 ^= char2 should be harmless regardless
whether char1 and char2 are signed or unsigned.

If CHAR_MIN equals -CHAR_MAX and the implementation does not support
negative zeroes, it's possible to generate a trap representation using
the bitwise operators. However, since for this the sign bit must be
set, and 's' and 't' must both be positive, there's no problem with the
original code.

.



Relevant Pages

  • Re: string operation??
    ... string, but on a character in that string. ... generate trap representations, for example, ... I'm not completely certain that bitwise operators count ...
    (comp.lang.c)
  • Re: string operation??
    ... string, but on a character in that string. ... bitwise or operation with the first two characters and storing the ...
    (comp.lang.c)
  • Re: string operation??
    ... string, but on a character in that string. ... bitwise or operation with the first two characters and storing the ...
    (comp.lang.c)
  • Re: dh, the daemon helper
    ... **ts is allowed to be a trap representation. ... If you're trying to classify a character that holds a trap ... I snip the rest since I generally agree. ...
    (comp.unix.programmer)
  • Re: dh, the daemon helper
    ... **ts is allowed to be a trap representation. ... It'd be more correct as *(unsigned char *)*ts. ... If you're trying to classify a character that holds a trap ...
    (comp.unix.programmer)