-1

could someone try explain the what the difference between these two pieces of codes is?

// Example program
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    char keypad[10][5]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    int idx = 2;
    string digits = "1324";
    int curidx=digits[idx] - '0';
    
    cout << curidx << endl;

}

In this case, with the inclusion on line 12, the output is 2.

// Example program
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    char keypad[10][5]={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    int idx = 2;
    string digits = "1324";
    int curidx=digits[idx];// - '0';
    
    cout << curidx << endl;

}

In this result, the output result is 50. What does the inclusion of - '0' do?

user438383
  • 5,716
  • 8
  • 28
  • 43
Shizo
  • 5
  • 3
  • Take a look at https://en.cppreference.com/w/cpp/language/ascii and notice the relationship between the numeric digits. If you subtract `'0'` from any of them it gives you the numeric value. – Retired Ninja Dec 25 '21 at 02:20
  • [Convert char to int in C and C++](https://stackoverflow.com/questions/5029840/convert-char-to-int-in-c-and-c) covers a lot of things, but has a few answers that explain it a bit. – Retired Ninja Dec 25 '21 at 02:23

1 Answers1

1

In C and Cpp, everything is inherently treated as a "number". Even char manipulations should be treated as number-operations...that makes it easier to logic-out the requirements.

Every char is indeed, an integer, equivalent to its ASCII value.

Hence, '2' = 50. Also, 'A' = 65 and 'a' = 97 and so on...

So, your operation '2' - '0' actually does 50-48, which results in 2

When you do not subtract and print '2' as integer, it prints its ascii value, which is 50. If you would print it as a char or string, it would have printed 2.

vish4071
  • 5,135
  • 4
  • 35
  • 65