-9

In this code snippet, what values do a and i have respectively and why?

int i = 1;
int a = i++;

Does a == 1 or a == 2 ?

Johan
  • 74,508
  • 24
  • 191
  • 319
  • 3
    You can answer the first part of the question by simply running the program – onteria_ May 24 '11 at 19:06
  • 2
    This is one of those things best tried rather than asking on here. It is called the postfix operator, and it happens after the assignment. So `a == 1` and `i == 2`. – pickypg May 24 '11 at 19:07
  • 10
    Or even by thinking. I'm surprised someone with 4K rep would ask this. –  May 24 '11 at 19:07
  • 1
    effort required in typing the question could have been better used to type code and test – deepsnore May 24 '11 at 19:08
  • @all, Don't have a c compiler here and I need to translate a piece of code into assembler. – Johan May 24 '11 at 19:10
  • @Johan If you have internet access, you do have a C compiler. –  May 24 '11 at 19:11
  • Relevant reading: [C#: what is the difference between i++ and ++i?](http://stackoverflow.com/questions/3346450/c-what-is-the-difference-between-i-and-i/3346729#3346729) (not C, but still interesting) – Kobi May 24 '11 at 19:12
  • @Neil, good point I don't know you I didn't think of that. I wonder if there's an online c-compiler that I can throw snippets into to see what code comes out. Yes, found it: http://www.comeaucomputing.com/tryitout/ – Johan May 24 '11 at 19:14
  • 3
    Try this one: http://ideone.com/n0W5X – Kobi May 24 '11 at 19:17
  • @Kobi, great link, works like a charm. – Johan May 24 '11 at 19:31

4 Answers4

6

a==1. And then, i==2

It would be a==2 if you did a=++i

Lucas
  • 2,886
  • 1
  • 27
  • 40
5

A will be one. This is called a post-increment. The variable i is only increased after being used. The opposite is called a pre-increment.

Mr47
  • 2,655
  • 1
  • 19
  • 25
2

a==1, i++ returns the value of i and then increments it. FYI, if you had ++i the opposite would be true, i would be incremented and then the value would be returned.

daalbert
  • 1,465
  • 9
  • 7
2
int i = 1;

i now has the value 1.

int a = i++;

a has the value of i++, which is 1 (i++ returns 1, then it increases the value of i by 1). i now increases with 1 and becomes 2.

At this point, a == 1, i == 2.

rid
  • 61,078
  • 31
  • 152
  • 193