Reputation: 83
Why do I have to typecast the pointer in the following example inside the code
function in order to return values of type char
since I already have declared it as a constant pointer to char in the function definition?
In particular cout << (*p + 1)
the result is in integer format, while when changing that to cout << (char) (*p + 1)
then the result is displayed in char format, since I am typecasting it.
Does the <<
operator have some default arguments as to what type to display?
#include <iostream>
using namespace std;
void code(const char* p);
int main()
{
code("This is a test");
return 0;
}
void code(const char* p)
{
while(*p)
{
cout << (*p + 1);
p++;
}
}
Upvotes: 0
Views: 71
Reputation: 19617
*p
is const char
and adding 1
(integer literal) promotes it to int
(See numeric promotions in this link). You have to cast it back to char
:
cout << static_cast<char>(*p + 1); // abandon C-style cast
And yes, std::ostream::operator<<
is overloaded to treat different types differently.
Upvotes: 5
Reputation: 2874
Change
cout << (*p+1);
to
cout << *(p+1);
This works for the reasons stated by @LogicStuff.
Upvotes: 0