Nikos Athanasiou
Nikos Athanasiou

Reputation: 31549

Subscripting a string literal

Is subscripting an alphanumeric a common/valid technique? And what are the implicit conversions that take place ? example :

#include <iostream>
using namespace std;

int main() 
{
    int k(2);
    cout << "Hello"[k] << endl;
    cout << (k-1)["Hello"] << endl;
    // your code goes here
    return 0;
}

Upvotes: 3

Views: 294

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 311068

Of course there is no greate sense to write

cout << "Hello"[0] << endl;

instead of simple

cout << 'H' << endl;

However sometimes there is something as

#define Hello "Hello"

in some (especially C) programs.

In this case there is some sense to write

cout << Hello[0] << endl;

However it would be much better to define

const char *Hello = "Hello";

or

const char Hello[] = "Hello";

There is no difference between

"Hello"[0]

and

0["Hello"]

because according to the C++ Standard

The expression E1[E2] is identical (by definition) to *((E1)+(E2))

However the second record only confuses readers of the code.

As for the conversion then lvalue of string literal "Hello" that has type const char[6] is converted to type const char *. and then expression *((E1)+(E2)) is calculated using the pointer arithmetic.

Upvotes: 3

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145389

It's not particular common to index literal strings, but it has its uses, e.g.

auto hex_digit( int const value )
    -> char
{
    assert( 0 < value && value < 0x10 );
    return "0123456789ABCDEF"[value];
}

Upvotes: 8

O. Jones
O. Jones

Reputation: 108796

It's certainly valid. Very little typecasting is involved.

Consider that the language element "Hello" actually means

  const char * anonymousVariable = "Hello";

Then anonymousVariable[1] yields a char with value 'e', and anonymousVariable[1123] yields something unpredictable.

Is it a good idea to write code this way? It may or may not be, depending on the pattern you're trying to use.

Upvotes: 0

Related Questions