As a beginner of learning C++, I am trying to understand the difference between an array of type char
and an array of type int
. Here is my code:
void IntArray () {
int array[5] = {5,6,7,8,9};
cout << "Print int array: " << array << endl;
cout << "Print int array[0]: " << array[0] << endl;
cout << "Print int array[0]+1: " << array[0]+1 << endl;
}
void CharArray () {
char array[5] = {'a', 'b', 'c', 'd', '\0'};
cout << "Print char array: " << array << endl;
cout << "Print char array[0]: " << array[0] << endl;
cout << "Print char array[0]+1: " << array[0]+1 << endl;
}
And here is the output:
Print int array: 0xbfd66a88
Print int array[0]: 5
Print int array[0]+1: 6
Print char array: abcd
Print char array[0]: a
Print char array[0]+1: 98
My questions are:
Why does the following output the string '0xbfd66a88'? I was expecting it to return the address of the first element in the array:
cout << "Print char array: " << array << endl;
Why does the following output '98'? I was expecting it to output the letter 'b':
cout << "Print char array[0]+1: " << array[0]+1 << endl;
1.
Because
char
arrays are treated differently to other arrays when you stream them tocout
- the<<
operator is overloaded forconst char*
. This is for compatibility with C, so that null-terminatedchar
arrays are treated as strings.See this question.
2.
This is due to integral promotion. When you call the binary
+
with achar
(with value 'a') and anint
(with value 1), the compiler promotes yourchar
to either asigned int
or anunsigned int
. Which one is implementation specific - it depends on whetherchar
is signed or unsigned by default, and whichint
can take the full range ofchar
. So, the+
operator is called with the values '97' and '1', and it returns the value '98'. To print that as achar
, you need to first cast it:See this question.
Okay let's go over each separately.
Here you print an int[] which goes into the
operator <<
overload that takes int*. And when you print a pointer you see a memory address in hexadecimal format.Here you print the first element of the array which is an
int
. As expected.Here you add 1 to the first element of the array and print the result, which is still an
int
. 5+1 becomes 6. No mystery here.This is a bit trickier. You print a
char[]
and there is a special overload foroperator <<
that takes aconst char*
and that one gets called. What this overload does is print each character beginning from the address where the pointer points until it finds a terminating zero.Here you print a
char
so the overload that takeschar
gets called. It prints the corresponding ASCII character, which is 'a'.Here the result of
operator+
is anint
because the literal 1 is anint
and thechar
value gets promoted to the wider type (int
). The result is 98 because the ASCII code of the letter 'a' is 97. When you print thisint
you just see the number.