[comp.lang.c] += in C

steves@ncr-sd.SanDiego.NCR.COM (Steve Schlesinger) (07/01/88)

I tried email this directly but it bounced.
Sorry (to the original poster) for the delay in answering.
Sorry to everyone else if it was aleady answered and I missed it.


In article <20039@beta.UUCP> you write:
>To some extent, the lack of detailed knowledge
>of C is my reason for not using it. (For example: why is 'a+=b' faster
>than 'a=a+b'?  Seems to me that the two are identical and should generate
>the exact same code.)


When optimized, yes they are the same.

Without optimization consider

	a[i][j] = a[i][j] + b
vs.
	a[i][j] += b

In the second case the address a[i][j] is computed only once and reused.
This is faster both at compilation and execution times.

An optimizer would convert the first to the second.
-- 

chris@mimsy.UUCP (Chris Torek) (07/01/88)

In article <2314@ncr-sd.SanDiego.NCR.COM> steves@ncr-sd.SanDiego.NCR.COM
(Steve Schlesinger) writes:
>When optimized, yes they [a=a+b and a+=b] are the same. ... consider
>	a[i][j] = a[i][j] + b
>vs.
>	a[i][j] += b
>
>In the second case the address a[i][j] is computed only once and reused.
>This is faster both at compilation and execution times.
>
>An optimizer would convert the first to the second.

(unless, of course, one or more of *a, i, and j have the `volatile'
attribute) [was this a good time not to post :-) ?]

Far more important than the `optimisation' is readability.  If I
mean add 3 to something, I should be able to write `add 3 to <...>'.
I can do it in COBOL; I ought to be able to do it in any supposedly
superiour language.

Quick, are both sides the same?:

	p->a[l+o[p->b]] = p->a[1+o[p->b]] + 3;
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris@mimsy.umd.edu	Path:	uunet!mimsy!chris

smryan@garth.UUCP (Steven Ryan) (07/02/88)

>In the second case the address a[i][j] is computed only once and reused.
>This is faster both at compilation and execution times.
>
>An optimizer would convert the first to the second.

Assuming none are *volatile*.

smryan@garth.UUCP (Steven Ryan) (07/03/88)

>	p->a[l+o[p->b]] = p->a[1+o[p->b]] + 3;

Difficult on this terminal anyway. It only has a one pixel difference:

             XX         X
              X   vs.  XX
              X         X

---------------------------------
Long live King George of Virgina!