|
From: Albert C. <al...@us...> - 2005-01-24 03:36:47
|
if(foo) foo=0; // foo was uninitialized This code is rather odd I admit, but it is has perfectly well-defined behavior. It initializes foo to 0, skipping the store if foo is already 0. |
|
From: Howard C. <hy...@sy...> - 2005-01-24 03:52:03
|
Albert Cahalan wrote: >if(foo) foo=0; // foo was uninitialized > >This code is rather odd I admit, but it is has perfectly >well-defined behavior. It initializes foo to 0, skipping >the store if foo is already 0. > Doesn't seem like it's worth spending any time to fix this. Better to fix the source code, it's just silly. Always faster to just store the value than to test/branch. -- -- Howard Chu Chief Architect, Symas Corp. Director, Highland Sun http://www.symas.com http://highlandsun.com/hyc Symas: Premier OpenSource Development and Support |
|
From: Albert C. <al...@us...> - 2005-01-24 04:41:08
|
On Sun, 2005-01-23 at 19:52 -0800, Howard Chu wrote: > Albert Cahalan wrote: > > >if(foo) foo=0; // foo was uninitialized > > > >This code is rather odd I admit, but it is has perfectly > >well-defined behavior. It initializes foo to 0, skipping > >the store if foo is already 0. > > > Doesn't seem like it's worth spending any time to fix this. Better to > fix the source code, it's just silly. Always faster to just store the > value than to test/branch. It's not always faster. Typically, memory access is a bottleneck. Not all the world has branch penalties like a Pentium 4. Suppose that foo is on a cache line that was already fetched for loads, so that isn't a complicating concern. The cost of doing the write will be: 1. cache line invalidates on other CPUs (and future reloads) 2. slowness in other code, as the write-out occupies the bus That all said, I ditched the code for excessive obscurity. (it IS in a hot path though, so I ought to benchmark) |
|
From: Chris S. <c.s...@co...> - 2005-01-24 04:02:44
|
On Sun, Jan 23, 2005 at 10:14:47PM -0500, Albert Cahalan wrote:
> if(foo) foo=0; // foo was uninitialized
>
> This code is rather odd I admit, but it is has perfectly
> well-defined behavior. It initializes foo to 0, skipping
> the store if foo is already 0.
No, it does NOT have well-defined behavior. It has a well-defined
post-condition - big difference. For example:
{
int foo;
if (foo)
do { foo++ } while (foo < MAX_INT);
foo = 0;
}
Has exactly the same well-defined post-condition as your example,
i.e. foo==0, and it also has exactly the same _undefined_ (depending
on stack-garbage) behavior. You cannot predict either code's actual
execution path, which IS its behavior.
Anyway, 'if (foo) foo=0' is more than just ill-defined, it's ugly: use
'foo=0'
-chris
|