Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is difference between ++i and i+=1 from any point of view

Tags:

c

operators

This is a question from kn king's c programming : a modern approach. I can't understand the solution given by him:-

The expression ++i is equivalent to (i += 1). The value of both expressions is i after 
the increment has been performed.

How do I understand this anyway?

like image 289
chanzerre Avatar asked Dec 01 '22 18:12

chanzerre


2 Answers

i = 10
printf("%d", i++);

will print 10, where as

printf("%d", ++i);

will print 11

X = i++ can be thought as this

X = i
i = i + 1

where as X = ++i is

i = i + 1
X = i

so,

printf ("%d", ++i); 

is same as

printf ("%d", i += 1);

but not

printf ("%d", i++);

although value of i after any of these three statements will be the same.

like image 187
thefourtheye Avatar answered Dec 19 '22 12:12

thefourtheye


The solution means to say that there is no difference, ++i has the same meaning as (i += 1) no matter what i happens to be and no matter the context of the expression. The parentheses around i += 1 make sure that the equivalence holds even when the context contains further arithmetics, such as ++i * 3 being equivalent to (i += 1) * 3, but not to i += 1 * 3 (which is equivalent to i += 3).

The same would not apply to i++, which has the same side effect (incrementing i), but a different value in the surrounding expression — the value of i before being incremented.

like image 26
user4815162342 Avatar answered Dec 19 '22 11:12

user4815162342