Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in statements adding 1 to string literal

Ive been giving the following assignment to explain what is happening in 3 statements but i can't figure it out.

cout << ("hello" + 1);    // ello
cout << (*"hello") + 1;   // 105
cout << (*("hello" + 1)); // e
  1. Why is number 2 a number instead of a character?
  2. does first one still have zero character? (to end string)
like image 444
user3984953 Avatar asked Aug 28 '14 01:08

user3984953


2 Answers

  1. *"hello" gives the first character of the string, 'h', of type char, with ASCII value 104. The integer promotion rules means that, when adding char and int, the char is converted to int, giving a result of type int. Outputting an int gives the numeric value.

  2. Yes. The string literal is an array ending with a zero character. Adding one to its address gives a pointer to the second character of the array; the remainder of the array is unchanged, so still contains the zero at the end.

like image 87
Mike Seymour Avatar answered Nov 07 '22 20:11

Mike Seymour


cout << ("hello" + 1);    // ello

You're incrementing a const char[] by 1, so you print everything but the first character (until you hit the null character

cout << (*"hello") + 1;   // 105

You dereference a const char[] here. The first character is an h, with ascii code 104. Add one and you get 105.

cout << (*("hello" + 1)); // e

Same thing as before, you dereference a const char[] but this time you increment by one first.

like image 6
Red Alert Avatar answered Nov 07 '22 20:11

Red Alert