Author: Robert Hyatt
Date: 21:53:44 07/04/03
Go up one level in this thread
On July 04, 2003 at 13:56:09, Normand M. Blais wrote:
>Hi,
>
>First, I would like to thanks everybody for their help. No one can succeed
>alone.
>
>The problem that I had was that my program would not run properly when compile
>with optimization for speed but would run ok in debug version or in release
>version with default optimization. I found that the problem was with a specific
>function and the way it was coded:
>
>// This fuction runs with no problem in debug version or release version with
>// default optimization.
>// But it fails in release version with optimization for speed.
>inline int s2i(const char *str)
>{
> // input: a square name (string) (ex: e4)
> // output: a square number (integer) (ex: 36)
>
> int sq = (*str - 'a') + (8 * (8 - (*(++str) - '0')));
>
> if (sq >= 0 && sq <= 63) return sq;
>
> return -1;
>}
>
The above has a gross assumption that is wrong. It assumes that C
evaluates an expression left to right. That is not guaranteed when
you turn an optimizer loose on this. The reference to str and ++str
are begging for trouble, as the ++str _could_ be done first which
would break the code.
The simple rule here is to _never_ use the ++/-- operator in a line
of code where the variable associated with ++/-- is referenced more than
once. Easiest fix is to remove the ++ and put that on a separate line
so that the order is known.
When you compile for debugging (or for profiling or whatever, or without
optimization) the compiler generally does do things left to right and
does redundant calculations without regard for efficiency. But once you
enable optimization, things change, and often in an unexpected way. Many
compilers don't optimize with debugging turned on as it makes it very tough
to map an assembly statement to a particular source line. But without the
debugging flag set, it can shuffle and eliminate until it is happy. And
that exposes the above "no-no" piece of code as bad.
>
>// This function runs fine (with or without optimization).
>inline int s2i(const char *str)
>{
> // input: a square name (string) (ex: e4)
> // output: a square number (integer) (ex: 36)
>
> int sq = (str[0] - 'a') + (8 * (8 - (str[1] - '0')));
>
> if (sq >= 0 && sq <= 63) return sq;
>
> return -1;
>}
>
>
>Why the first version of the function causes problem is not clear to me. Anyway.
>I felt that it is fare for me to share this information taking into account that
>I benefit greatly from others.
>
>Thank you,
>
>Normand
This page took 0 seconds to execute
Last modified: Thu, 15 Apr 21 08:11:13 -0700
Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.