can i use a[-1] to refer to the last member?

can i use a[-1] to refer to the last member?
i am just used to this ..
however..i got something odd..
1
2
3
int t=432;
int a[4];
printf("%d",a[-1]);// I got 432 

closed account (28poGNh0)
No you can not ,and perhaps you got 432 ,just because you compiler did put the address of "t" aside the address of " a[0]" ,so when you write a[-1] you access the value of "t".

that what I think
that's impossible, did you try to run it again and had the same results?
maybe the compiler assigns random value to each elements of the array and luck put the value of t in the 1st element of the array


a[-1] ??
Last edited on
can i use a[-1] to refer to the last member?

No. This is unreliable behavior.

When a function is called, memory is allocated for the function's local variables. This portion of memory is called the "stack".

To my knowledge, the compiler doesn't need to maintain a certain order of local variables on the stack. So your code may not work for other people, and may not work for you either if you enable optimizations.
1
2
3
int& operator[](int index){
   return v[ (index%size+size)%size ];
}
Topic archived. No new replies allowed.