4 ms·
char toupper(char c) { if (c >= 'a' && c <= 'z') { return (c - 'a') + 'A'; else { return c; } }
by XMPPwocky 7y ago
char toupper(char c) {
if (c >= 'a' && c <= 'z') {
return (c - 'a') + 'A';
else { return c; }
}
- thaumasiotes 7y agoIt's worth mentioning explicitly that while `c - 'a'` is the more obvious application of character addition in your example, `c >= 'a'` is another one that's even more common. Pretty much everyone immediately understands that we want to be able to sort characters.
- XMPPwocky 7y agoYeah- but the problem of poorly-defined result type isn't present for comparison operators, since a bool is a b... oh, hold on, C. Since an int is an int. Sigh.
- slavik81 7y agoIn C, 'a' is an int so most of those are not char/char operations. In C++, 'a' is a char and the comparison result is a bool, though it doesn't really make a difference in that function.
- thaumasiotes 7y agoWhen you're sorting, you're generally comparing two variables to each other, as opposed to comparing one variable to a literal constant.
- brudgers 7y agoThe Erlang is Perlilous: toUpper(char) -> $ + char. % It's "$ "
- kccqzy 7y agoYou showed an example of subtracting a character from another. The GP asked for an example of adding two characters.
- tlb 7y ago(c - 'a') + 'A' contains both
- XMPPwocky 7y agoI thought about saying (c + 'A') - 'a' to make this more clear, but I think that's actually UB with signed chars- e.g. for c='a', 'a'+'A' exceeds the range of a signed 8-bit value! Promotion should save us here, but that's a bit too yikes-y for my comfort.
- kccqzy 7y agoIt does not. Subtracting a char from a char involves usual arithmetic conversions as well and the result is typically an int. Next, you have addition between an int and a char.
- deleted 7y ago[deleted]
- _kst_ 7y agoThat relationship is valid for ASCII, and for character sets derived from ASCII, but it's not guaranteed by the language. In particular, in EBCDIC the alphabet is non-contiguous.
- XMPPwocky 7y agoAbsolutely- this code only works with ASCII-ish charsets.
- moring 7y agoAdding two characters isn't strictly needed for that -- you're relying on the assumption that (c - 'a') is of type character, but it's actually the offset between two characters. The rules for those two types would be: char + char = invalid char + offset = offset + char = char offset + offset = offset char - char = offset char - offset = char offset - char = invalid offset - offset = offset Given that, (c - 'a') + 'A' is perfectly valid without adding two characters. edit: formatting