Re: Use of C++ container iterator with negative 1 index in X3 examples

Henri Menke <[email protected]> Sun, 10 Jun 2018 16:14:31 +1200
Newsgroups gmane.comp.parsers.spirit.general
Message-ID <[email protected]>
On 06/10/2018 12:58 PM, Chris Mileto wrote:
> In the Calc9 example code file vm.cpp (and in many other X3 examples) the
> syntax: "stack_ptr[-1] = some_value;" is used, where stack_ptr is defined as
> std::vector<int>::iterator stack_ptr.
> 
> According to the standard as I understand it, iterator indexing begins at
> zero.
> 
> I can see that it compiles and executes at least for my Microsoft  Visual
> Studio 2017 compiler, but is the use of a negative index valid C++ syntax?
> If so what does it mean?

stack_ptr[-1] is just syntactic sugar for *(stack_ptr - 1) which is
perfectly legal pointer arithmetic.  It means go back one from where the
pointer currently is.  In this case the stack_ptr probably points to the
top of the stack, so the value at -1 is the one below.

> 
> Thanks for any insight,
> Chris
> 
> 
> ------------------------------------------------------------------------------
> Check out the vibrant tech community on one of the world's most
> engaging tech sites, Slashdot.org! http://sdm.link/slashdot
> _______________________________________________
> Spirit-general mailing list
> [email protected]
> https://lists.sourceforge.net/lists/listinfo/spirit-general
> 


------------------------------------------------------------------------------
Check out the vibrant tech community on one of the world's most
engaging tech sites, Slashdot.org! http://sdm.link/slashdot