0

I tried this in many ways and it seems simple enough for this problem not to happen. Where did the 54 and 56 come from when I assigned the value 6 and 8?

#include <iostream>
using namespace std;

int main()
{
    int x = '6', y = '8';
    while(1){
        cout << "7" << endl;
        cout <<  y  << endl; 
        y += 1;
        cout << "7" << endl;
        cout <<  x  << endl; 
        x -= 1;
        }
}
273K
  • 29,503
  • 10
  • 41
  • 64
  • 6
    Do you know the difference between the number 6 and the character literal `'6'`? Take a look at an ASCII chart. – Retired Ninja Mar 30 '23 at 00:45
  • 1
    What do your learning material say about the different basic types, like `int`, `double` or **`char`**? – Some programmer dude Mar 30 '23 at 00:46
  • 1
    So you started studying C++ with bad habits. [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – 273K Mar 30 '23 at 00:46
  • 1
    "Where did the 54 and 56 come from when I assigned the value 6 and 8?" They came from when you assigned 54, by using `'6'` to mean the integer value 54, and 56, by using `'8'` to mean the integer value 56. Notice how the compiler **did not complain** about assigning something inside quotes to an integer? As an experiment, try using e.g. `int x = 'a';`. – Karl Knechtel Mar 30 '23 at 00:56
  • @KarlKnechtel I dont think any of those dupes relate to this question. I imagine there might be a dupe out there, but none of these are to do with assigning one type to another and printing. – Fantastic Mr Fox Mar 30 '23 at 01:11
  • Does this answer your question? [Difference between char and int when declaring character](https://stackoverflow.com/questions/37241364/difference-between-char-and-int-when-declaring-character) – phuclv Mar 30 '23 at 01:37
  • @FantasticMrFox I tried my best to find the closest thing I could. I don't regularly browse c or c++ tags (although I can use those languages) so I don't have a canonical set handy; but this is such a "classic" issue that there has got to be a canonical for it. – Karl Knechtel Mar 30 '23 at 03:22
  • Does this answer your question? [Single quotes vs. double quotes in C or C++](https://stackoverflow.com/questions/3683602/single-quotes-vs-double-quotes-in-c-or-c) – pppery Mar 30 '23 at 03:39

1 Answers1

3

you need to be aware of types. You have

int x = '6';

this says

The variable x, of type int (an integer) is equal to the value of the char type character 6.

If you look at an ascii table you will see that the integer value for the char '6' is actually 54 which is the number you are getting. If you use the correct type:

char x = '6';

Then when you give it to std::cout you will get the right output.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175