Hello friends,

I have a code snippet related to pointer increment and decrement.

int arr[] = {1,2,3,4,5};
int *ptr;
ptr  = arr + 2;
printf("%d %d %d %d %d %d\n",ptr,(ptr+1),ptr--,ptr,ptr++,++ptr);

It is giving console output as:
1245020 1245024 1245024 1245020 1245020 1245020

I am a bit surprised with the third output 1245024 for ptr--
My expectation was 1245016.
(Right to left priority for unary operators).

There is no change in fifth and sixth outputs also.Why?

Tried it in VS2008.

7 Years
Discussion Span
Last Post by vinodxx

See http://www.embedded.com/story/OEG20020429S0037 (it happens to be an embedded article but it still applies). When you are passing parameters to a function they are not guaranteed to be evaluated from left to right, right to left or any other order. I tried it on 2 different compilers (VC++ 2008 Express and gcc 3.4.2) and they gave 2 different answers so it's one of these "unspecified" kind of situations (from the article) and can't be relied upon. The best solution would be to perform the arithmetic for one step, print it out, step two, etc.

Edited by jonsca: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.