2

I am studying for a midterm and one of the questions is Which of the following statements will increment a value in the array, and leave the pointer address unchanged? Circle 0 or more.

int array[10];
int * ptr = array;

1) *ptr++;

2)(*ptr)++;

3)*++ptr;

4)++*ptr;

I have seen 1 and 2 used before and I believe it's just getting the de-referenced values without changing the pointer. But I was surprised to find 3 and 4 is actually valid and I am confused as to how to understand or even read it? Is it the same thing? I believe the answer is that all 4 of them are valid.

2
  • 7
    You can always try it out. Commented Oct 21, 2013 at 1:23
  • 5
    Knowing the precedence of operators will help you get started. Commented Oct 21, 2013 at 1:26

2 Answers 2

2

http://en.cppreference.com/w/cpp/language/operator_precedence will be helpful to you. Read through it and put the parenthesis in to the examples based on the precedence of the operators and everything will hopefully make some sense.

The first would become *(ptr++) for instance.

Sign up to request clarification or add additional context in comments.

Comments

1

Every C++ expression yields a value (main effect). There can also be side effects (as in the examples above) which occur before (e.g. pre-increment in examples 3 and 4) or after (e.g. post-increment in examples 1 and 2) the main effect. So in your examples:

1) side effect occurs last:

main effect: dereference ptr to get array[0]

side effect: post increment ptr by 4 bytes (on a 32 bit machine)

2) side effect occurs last:

main effect: dereference ptr to get array[0]

side effect: post increment *ptr (=array[0]) by 1

3) side effect occurs first:

side effect: pre increment ptr by 4 bytes (on a 32 bit machine)

main effect: dereference *ptr to get array[0]

4) side effect occurs first:

side effect: pre increment *ptr (= array[0]) by 1

main effect: dereference *ptr to get array[0]

Notice the main effect is obtained by ignoring the side effect operator (++) and is therefore the same in all cases. The main effect is often combined with assignment as in:

int y = *++ptr;    // ptr is incrented to point at array[1] and then y becomes equal to *ptr (= array[1])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.