Current-Users archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: Casting ctype lookups



On Thu, 15 Nov 2012, D'Arcy J.M. Cain wrote:
$ gcc -funsigned-char -Wall -Werror -o t t.c && ./t

Does the same thing.  The function version still works.  It may be that
gcc is the problem, at least in this case, but gcc is what we provide.

The code in "t.c" is the problem.  Let me try to explain it again.

The gcc warning under discussion essentially means "You are using a plain char here, and it would be bad if it flipped between signed and unsigned without your knowledge, and that could happen if the code is moved to a different platform or built with different options, so you should explicitly choose either 'signed char' or 'unsigned char', don't just use 'char'."

Passing a negative-valued char or a negative-valued signed char to a ctype function invokes undefined behaviour (or just does the wrong thing, if the value happened to be equal to EOF). Invoking undefined behaviour, or getting the wrong result, is bad. Therefore, you should not pass negative valued chars or signed chars to ctype functions.

Strictly speaking, if you are are certain that the the char or signed char has a non-negative value, then passing it to a ctype function is OK. However, code gets copied around, and somebody else, or even you yourself, may later use the same code in a context where they can't be certain that the values will never be negative. Then the copied code will invoke undefined behaviour. That would be bad. To avoid the undefined behaviour in derivative code, the original code should not merely be sure that the value is non-negative; it should use a type that cannot have negative values. Therefore, it should not use signed char or plain char when calling ctype functions.

If you get the gcc warning that started this thread, then you have violated the guideline in the previous paragraph: you have passed a (plain) char to a ctype function.

--apb (Alan Barrett)


Home | Main Index | Thread Index | Old Index