Jasdeep Singh Arora
Jasdeep Singh Arora

Reputation: 563

Function call with array index

I came across with a statement with function call and as well as array index in the kind of code mentioned below .In this the statement s=o.init()[-1] is returning value of a1[0]. I am not cleared with the concept of how it is working, what this statement o.init()[-1] will do ?, i know 0.init() will give a call to function but what does [-1] specify? Pls help to solve this query?

#include<iostream>
using namespace std;

class a
{
  char a1[1000];

  public:
  a()
 {
    a1[0]='a';
 }
  char* init()
  {
     cout<<"value of a1 is"<<a1<<endl;
     return a1+1;
  }
};

int main()
{
   a o;
  char s;
  s=o.init()[-1];


cout<<"value of s  is"<<s<<endl;
}

Upvotes: 0

Views: 808

Answers (3)

Alexey Frunze
Alexey Frunze

Reputation: 62048

init() returns a pointer to a1[1]. o.init()[-1]; subtracts 1 from that pointer (so, you get a pointer to a1[0]) and dereferences it and you get a1[0].

Upvotes: 2

The return value of the method is char*. So the index operator subtracts one from the address, and dereferences it.

Upvotes: 1

Alon
Alon

Reputation: 1804

init returns a char* so init()[-1] will just take the pointer one char backwards in the memory.

Imagine it like:

char* arr = o.init();

and then:

arr--;

As you can see, your function returns the array+1, so in order to take 'a', or rather the first value, you'll have to go one step backwards

Upvotes: 1

Related Questions