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
*"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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With