4

I'm new to C++. I was wondering why I get A2105376B when I run the following code:

#include <iostream>
int main(){

  std::cout <<'A' << '   ' <<'B'<<std::endl;
  return 0;

}

Thanks in advance!

wavecommander
  • 164
  • 15
Alih3d
  • 45
  • 3

1 Answers1

6

This ' ' is a multicharacter character literal that has the type int and an implementation defined value.

It seems you mean one-byte character literal ' ' or a string literal " "

From the C++ Standard (2.13.3 Character literals)

2 A character literal that does not begin with u8, u, U, or L is an ordinary character literal. An ordinary character literal that contains a single c-char representable in the execution character set has type char, with value equal to the numerical value of the encoding of the c-char in the execution character set. An ordinary character literal that contains more than one c-char is a multicharacter literal. A multicharacter literal, or an ordinary character literal containing a single c-char not representable in the xecution character set, is conditionally-supported, has type int, and has an implementation-defined value.

Here is a demonstrative program that outputs an integer object if it is initialized by ASCII values of three spaces.

#include <iostream>

int main() 
{
    int x=  0x202020;

    std::cout << x << '\n';
    std::cout << '   ' << '\n';

    return 0;
}

The program output is

2105376
2105376
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    can you expand more on what the value could be like? and how does it get converted to int? or how is it interpreted? just for my own understanding – Waqar Apr 10 '20 at 19:43
  • 2
    Well, @Waqar just try, as a mental experiment, an attempt to wrap your brain how we humans take individual digits 4, 6, and 8, and get one number 468 out of it. Same thing here, except that the digits are individual bytes, that each can have 256 different values instead of ten different values, since each character is just a byte. Except for 256 values instead of 10, the underlying math is identical. – Sam Varshavchik Apr 10 '20 at 19:46
  • 1
    @SamVarshavchik: but it is just **one** possible implementation. returning always 42 would also be valid... – Jarod42 Apr 10 '20 at 19:51
  • 1
    @Waqar See my updated post. – Vlad from Moscow Apr 10 '20 at 19:51
  • Thanks very much @VladfromMoscow ! – Alih3d Apr 10 '20 at 20:09