This is a borrowed function from this forum and is part of a checkers games. I've been working with it as a program to understand ASCII and Arrays.
The Line:
x=letter-'A' +1;
later...
return (x -1);
Question: Why add 1 to the value and then remove it later?
Context: User is asked to enter A - H. As a function this will be used to identify a column in an array. When I adjusted the code I removed the +1 and -1 as you can see below. Is there a reason to keep these in?
#include <iostream>
using namespace std;
int main (int argc, const char * argv[])
{
//This program asks for a letter between A - H.
//It converts the entry to uppercase and assigns the ASCII number.
//This is useful for representing a letter coordinate to an eight column array.
//Example: a checker board.
char letter;
int x = 8;
cout << "A - H: ";
//Loops until a value within range is provided
//toupper() converts the char to uppercase incase lowercase is entered
while(x<0 || x >7)
{
cin >> letter;
letter = toupper(letter);
x=letter-'A';
if (x<0 || x>7) {
cout << "Please give a letter between A - H: ";
}
}
//displays the results
cout << letter << " is column " << x << "\n";
//returns the column number (for future function use)
return(x);
}
BTW... I notice if I don't assign a value to x it defaults to 0. This "broke" the intended logic of these while() and if() statments, and maybe this is why +1 is useful?