const char*

Hello, new member here currently learning C++ in self study.
I have the following code:

1
2
3
4
5
  const char * pchar = "123456789";
  cout << pchar << "/n"; // output: 123456789
  cout << pchar + 1 << "\n"; // output: 23456789, move pointer
  cout << *pchar << "\n"; // output: 1, deref. pointer
  cout << (*pchar) + 1 << "\n"; // output: 50 ??? 


Everything is clear to me (I think), but I don't understand the output of the last cout statement. Could someone explain ?
Thanks.
Value of *pchar ('1') got promoted to int (49 in ASCII code) and then 1 added. Result of expression is int.
Thanks.
It's not fully clear to me yet.

I figured when I want to get what I actually expected ('2') I need to do an explicit cast like

 
cout << char((*pchar) + 1) << "\n"; // output: 2 


But I don't understand why the promotion is happening in the first place.
Could you elaborate ?

You are adding two types which are not directly compatible: char + int. Smaller one is converted to larger one: (charint) + int. Result is a common type: int.

Just to warn you about second quirk: any integral type smaller than int is pomoted to int in any operation. So char + short result is int, as both operands promoted to int. That is what happened in your case, actually.
Дякую!

Дійсно дивно!

Незрозуміло std :: cout << * pchar << "\ n"; // Output: 1, deref. pointer

Як це 1 чекаючи на зразок A34DFD45

Взагалі незрозуміло чого 50 ??
Thanks!

Really amazing!

It is not clear std :: cout << * pchar << "\ n"; // Output: 1, deref. pointer

As it is expecting one like A34DFD45

In general, it is not clear what 50 ??
Ah so we're talking about Implicit conversions like mentioned here ?

http://en.cppreference.com/w/cpp/language/implicit_cast

That's a topic new to me, have to read up on it.

If that's it, clear in principle now what's happening, so I''ll mark it as solved.

Thanks again.
Last edited on
Yes, those are implicit conversions. They are everywhere. It is realy hard to write codewithout using at least some of them.
Got it, thanks.
мабудь неможна разименувати *pchar.
Чому неможна я навіть гадки не маю. Але результат у мене такий же самий.

rightly so can not dereferenced
* pchar.
Why can not I even have no idea. But the result I have this same.

- pchar 0x00417838 "123456789" const char *
49 '1' const char
Topic archived. No new replies allowed.