Fred,

You are correct in all of your examples.  That is why many standards specify things like /multiple function calls should not be used in a single expression/.  The compiler will optimize out any unecessarry memory reads and writes so rewriting:

X = foo() + bar();

as

X = foo();
C += bar();

Will force the correct order of execution of the functions while not taking any more CPU cycles.

          Mike

On 8/15/2024 7:32 PM, Fred Cisin via cctalk wrote:
On Thu, 15 Aug 2024, Mike Katz wrote:
C has specific specifications for what is promoted when and how. They are not ambiguous just not known by many. I worked for a C compiler company so I'm may be a bit more familiar with the actual C specs and how the compiler works. However, I totally agree with you.  I heavily typecast and parenthesize my code to avoid any possible ambiguity.  Sometimes for the compiler and sometimes for someone else reading my code.

I will readily concede that ANSI C has fewer problems with ambiguous code than the K&R C that I learned.

But, for example, in:
X = foo() + bar();

has it been defined which order the functions of foo() and bar() are evaluated?  Consider the possibility that either or both alter variable that the other function also uses. (Stupidly simpe example, one function increments a variable, and the other one doubles it)

As another example of code that I would avoid,
int x=1,y=1;
x = x++ + x++;
y = ++y + ++Y;
give 2, 3, 4, or 5?
is heavily dependent on exactly when the increments get done.

But, thorough careful typecasting, use of intermediate variables, etc. can eliminate all such problems.
'course "optimizing compilers" can (but shouldn't) alter your code.

If you don't explicitly specify exactly what you want, "C gives you enough rope to shoot yourself in the foot" (as Holub titled one of his books)


But, I've always loved how easily C will get out of the way when you want to get closer to the hardware.

--
Grumpy Ol' Fred ci...@xenosoft.com

Reply via email to