Character offset in C ++

I tried to write a function to easily switch characters (left or right, depending on the shift parameter in the next function). Uppercase letters remain uppercase. Here is my approach:

char encodeCaesarCipherChar(char ch, int shift) { char result; if (!isalpha(ch)) return ch; result = ch + shift; if (islower(ch) && result < 'a') { result += int('z') - 1; result -= int('a'); } else if (islower(ch) && result > 'z') { result -= int('z'); result += int('a') - 1; } else if (isupper(ch) && result < 'A') { result += int('Z') - 1; result -= int('A'); } else if (isupper(ch) && result > 'Z') { result -= int('Z'); result += int('A') - 1; } return result; } 

This function stops working properly when the input character is 's' or higher. Can someone point out that the problem is for my approach?

Thanks in advance.

+6
source share
1 answer

's' + 13 will overflow the signed char . Store the result in int and enter char after setting the number and before returning.

+6
source

Source: https://habr.com/ru/post/953818/


All Articles