3

This is a very simple question but even have some doubt in sequence point.

int a[3] = {1,2,4}; printf("%d",++a[1]); 

o/p

3 

Is this a valid c statement, I am getting output 3, which means it is same as

++(a[1]) 

But how is this possible as we have a pre-increment operator which has to increment the a first then the dereference has to happen.

Please correct my doubt. How we are getting 3?

2
  • 1
    a is not even an assignable lvalue, so even if the precedence laws were different you could not get 4 . (you can't increment an array) (you cannot increment the numeric literal 1 either) Commented Jan 24, 2015 at 14:36
  • @wildplasserr : Ya got it.. Commented Jan 24, 2015 at 14:38

4 Answers 4

7

Behavior is well defined. Operator [] has higher precedence than prefix ++ operator. Therefore operand a will bind to []. It will be interpreted as

printf("%d", ++(a[1])); 
Sign up to request clarification or add additional context in comments.

Comments

4

Your parentheses are right, your rationale for what you think should happen obviously wrong.

If you were right, and prefix-increment had higher priority than indexing, you would get a compiler-error for ill-formed code, trying to increment an array.

As-is, there's absolutely no chance for sequencing-errors or the like leading to UB.

Comments

1

That's how pre increment operator works. Its similar to ++count. So here your value at a[1] (as [] has higher precendence than ++) get incremented and then its printed onto the console.

Comments

1

As you can see here: http://en.cppreference.com/w/cpp/language/operator_precedence

The operator [] has a higher precedence then ++

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.