Member of The Internet Defense League Últimos cambios
Últimos Cambios
Blog personal: El hilo del laberinto Geocaching

Re: Pls. Help. If a=10; then why is (++a)+(++a) == 24 and not 23 ???

Última Actualización: 25 de Septiembre de 1.997 - Jueves

Message-ID: <330C412A.1172@argo.es>
Date: Thu, 20 Feb 1997 11:18:50 -0100
From: Jesús Cea Avión <jcea@argo.es>
Organization: Argo Redes y Servicios Telematicos, S.A.
Newsgroups: comp.lang.c
To: Raghav Vinjamuri <raghav@pyramid.com>
Subject: Re: Pls. Help. If a=10; then why is (++a)+(++a) == 24 and not 23 ???
References: <5egse1$3b3@halley.eng.pyramid.com>
 

> I am trying to figure out why the following code displays 24
> and not 23 -- as I would expect.
>
> void main() {
> int a=10;
> printf("%d\n", ((++a)+(++a)) );
> }

I found a related problem with pointers more than a year ago. My code was something like this:

a=(*p++)<<8+(*p++);

It try to solve the following problems:

  1. Missaligned operands
  2. big/little endian

My usual programming environment is Motorola 680x0 and Sun Sparc, and the code above ran smoothly. Nevertheless I tried to compile it under Windows using Borland C and it didn't work...

I finally discover the "bug": Borland C updates ALL the preincrement/decrement *before* the statement, and ALL the postincrement/decrement after that.

I hate that fact, but I studied the ANSI C standard and it doesn't forbid that. It only said (I don't remember it exactly) that pre and post operators must be updated before and after the use of their operands, but it doesn't state EXPLICITY that the compiler must do that IMMEDIATELY before or after.

Just another problem for portable code.

BTW, I corrected my code writing:

a=(*p<<8) | *(p+1);
p+=2;

or something like that. Not very elegant, but it is truly portable (I think) and my optimizer (Motorola 68030 processor) generates the *SAME* code:

clr.w d0
move.b (a0)+,d0
asl.w #8,d0
or.b (a0)+,d0

The first instruction is superfluous because the ASL opcode, but I don't complain...

--
Jesus Cea Avion                         _/_/      _/_/_/        _/_/_/
  jcea@argo.es                         _/_/    _/_/  _/_/    _/_/  _/_/
                                      _/_/    _/_/          _/_/_/_/_/
PGP Key Available at KeyServ   _/_/  _/_/    _/_/          _/_/  _/_/
"Things are not so easy"      _/_/  _/_/    _/_/  _/_/    _/_/  _/_/
"My name is Dump, Core Dump"   _/_/_/        _/_/_/      _/_/  _/_/
"El amor es poner tu felicidad en la felicidad de otro" - Leibnitz



Python Zope ©1997 jcea@jcea.es

Más información sobre los OpenBadges

Donación BitCoin: 19niBN42ac2pqDQFx6GJZxry2JQSFvwAfS