Reputation: 113
#include<iostream>
using namespace std;
int main()
{
int arr[128];
arr['a'] = 101;
cout<<arr['a'];
return 0;
}
So i was experimenting around and found that characters can be used as indices in arrays instead of conventional whole numbers. This program gives the correct output i.e 101 which is correct.
But how does this all work? Like in terms of space allocation and reference to that element.
Questions:
Upvotes: 2
Views: 315
Reputation: 234715
'a'
is a char
type with an implementation defined numeric value (depends on the character encoding used on your platform: in ASCII, it's 97).
That numeric char
is used in the evaluation of arr['a']
. If you're fortunate, that will give you an element of the arr
. If the value is outside the bounds of arr
then the behaviour of the program is undefined.
Upvotes: 8
Reputation: 311468
char
s are just smaller int
s with a fancy way of printing them. A char
in fact holds the ASCII value of the character it represents. a
has the ASCII value of 97, so your snippet is in fact equivalent to:
int arr[128];
arr[97] = 101;
cout<<arr[97];
Upvotes: 4