-5

Help me understand the following:

cout<<'a'; //prints a and it's okay but
cout<<'ab'; //prints 24930 but I was expecting an error due to term 'ab' having two character in single quote
cout<<'a'+1; //prints 98 
cout<<"ab"; // prints ab and it's okay but
cout<<"ab"+1; // prints b, why?
cout<<"a"+1; // prints nothing ?
cout<<'a'+'b'; // prints 195 ?
cout<<"a"+"b"; // gives error ?

Please help me to understand all these things in details. I am very confused. I would be very thankful.

roschach
  • 8,390
  • 14
  • 74
  • 124
GKS
  • 35
  • 5
  • 9
    Sounds like you could use a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver Dec 17 '18 at 14:34
  • 1
    The `"ab"+1` and `"a"+1` cases are pointer arithmetic: you're advancing the pointer by one so that it starts at the second character, or in the second case starts at the end-of-string nul character. You can't concatenate strings like that in C++ in the last case, nor can you add a pointer to a pointer like you can add an int to one. – Rup Dec 17 '18 at 14:37
  • 1
    value of `'a'` in ascii is `97` (and `98` for `'b'`). That explains `'a' + 1` and `'a' + 'b'`. – Jarod42 Dec 17 '18 at 14:49
  • 1
    'ab' has no defined meaning in C++, but some compilers allow it. What it means depends on the compiler. – john Dec 17 '18 at 14:53
  • @Jarod42 And the operands are implicitly converted to `int` because of *integral promotion*. – LogicStuff Dec 17 '18 at 14:54
  • I would recommend you to choose one of the books for beginners and start there. [C++ Books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – VictorHMartin Dec 17 '18 at 15:31
  • 1
    @john -- `'ab'` is a [multicharacter literal](https://en.cppreference.com/w/cpp/language/character_literal). Every conforming compiler allows it. Its value is implementation defined. – Pete Becker Dec 17 '18 at 16:29

1 Answers1

5

'a' is a char type in C++. std::cout overloads << for a char to output the character, rather than the character number.

'ab' is a multicharacter literal in C++. It must have an int type. Its value is implementation defined, but 'a' * 256 + 'b' is common. With ASCII encoding, that is 24930. The overloaded << operator for an int outputs the number.

'a' + 1 is an arithmetic expression. 'a' is converted to an int type prior to the addition according to the standard integral type promotion rules.

"ab" + 1 is executing pointer arithmetic on the const char[3] type, so it's equivalent to "b". Remember that << has lower precedence than +.

"a" + 1 is similar to the above but only the NUL-terminator is output.

'a' + 'b' is an int type. Both arguments are converted to an int prior to the addition.

The arguments of "a" + "b" decay to const char* types prior to the addition. But that's the addition of two pointers, which is not valid C++.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483