Difference in statements adding 1 to a string literal

Ive given the following task to explain what happens in 3 statements, but I can not figure it out.

cout << ("hello" + 1); // ello cout << (*"hello") + 1; // 105 cout << (*("hello" + 1)); // e 
  • Why is number 2 a number instead of a character?
  • at first still have a null character? (to end the line)
+6
source share
3 answers
  • *"hello" gives the first character of the string 'h' type char with an ASCII value of 104. Integer promotion rules mean that when char and int added, char converted to int , giving an int type result. The int output gives a numerical value.

  • Yes. A string literal is an array ending with a null character. Adding one to its address gives a pointer to the second character of the array; the rest of the array does not change, so zero remains at the end.

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

You increase the number of const char[] by 1, so you print everything except the first character (until you hit the null character

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

Here you are casting const char[] . The first character is h, with an ascii code of 104 . Add one and you get 105 .

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

Same as before, you cast const char[] , but this time you increment by one.

+6
source

hello is const char * .

  • Why 2 - number → * "hello" will be the value at the base address, which is the value of ascii h (104), so 104 +1 = 105

  • Yes, you are now pointing to e , not h .

0
source

Source: https://habr.com/ru/post/974447/


All Articles