Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Objective-C Basics (Retired) Fundamentals of C Operators and Expressions

2 question for operator and expression.

  1. int a = 9; Why does c = 9 and a = 10 when I enter this: c = a++; why isn't it suppose to be c = 10 and a = 9 since if c = a +1; and original value of a = 9, what is the difference between auto increment, and how does the logic works? and why if we enter ++a the value of a and c would be 10. Again, what is the logic?

  2. why when i declare an integer and the value is 3/4 it will just be 0. even it is converted to int, it should be 1 since 0.75 is greater than 5, which should round up to the next number. And why is it when i declare a float and the value is 3/4 is 0 as well? isn't it suppose to be 0.7500, i tried inserted 3.0/4 or 3/4.0 and it works. What is the logic behind again? Dino Paškvan

1 Answer

There are two increment operators in C. A prefix operator (++number) and a postfix operator (number++).

The postfix operator, the one you used, will return the value of the number and then increment it. So, your variable a gets incremented after its value is assigned to c. That's why c is still 9 and a becomes 10.

The prefix operator first increments the number and then returns the value of the incremented number. So when using an expression like: c = ++a, both values will be 10.

As for your second question. When two integers are divided in C, any fractional part gets discarded. This is called truncation to zero or flooring. Basically, anything past the decimal mark is discarded.

Even if you do this: float b = 3/4; you are still doing arithmetic operations with integers and once the operations are done, you assign the result to the float variable. To let the compiler know you are doing arithmetic operations with floats, write it like this: float b = 3.0/4.0;. Specifying the decimal mark makes your code easier to read and troubleshoot.

Wow! You are really amazing! How do you know so much stuff? You are so great!!! Thanks I learn a lot from you!!!