comp.lang.c
[Top] [All Lists]

Re: Implementation-defined behaviour

Subject: Re: Implementation-defined behaviour
From: Flash Gordon
Date: Sat, 29 Mar 2008 08:10:44 +0000
Newsgroups: comp.lang.c


pete wrote, On 29/03/08 01:27:
Harald van =?UTF-8?b?RMSzaw==?= wrote:
On Fri, 28 Mar 2008 16:44:12 -0500, pete wrote:
Ioannis Vranos wrote:
K&R2 mentions the following:

"printf("%d %d\n", ++n, power(2,n));   /* WRONG */

can produce different results with different compilers,
depending on
whether n is incremented before power is called".

That's why I call it implementation-defined behaviour.
It's unspecified behavior.
The power(2,n) function call,
introduces a sequence point that the other
code examples don't have. This is all about sequence points.
If arguments are evaluated strictly from left to right (nothing wrong
with that), here are the steps:
- evaluate "%d %d\n"
- evaluate ++n
- evaluate 2
- evaluate n
* call power
* call printf

The call to printf starts before any of its arguments are evaluated.
power returns before printf does.

That is not what the standard says. The standard says:
4 An argument may be an expression of any object type. In preparing for
  the call to a function, the arguments are evaluated, and each
  parameter is assigned the value of the corresponding argument.81)

It goes on to say:
10 The order of evaluation of the function designator, the actual
   arguments, and subexpressions within the actual arguments is
   unspecified, but there is a sequence point before the actual call.

So in the above evaluating the parameters to the power function is explicitly *required* to take place before the sequence point of calling the function.

There is not necessarily
any sequence point between the evaluation of ++n
and the evaluation of n, unless I'm missing something.

There are only two different outputs that the above quoted
C statement can produce.
The choices need not be documented.
That's unspecified behavior.

No, it is undefined behaviour because there is no sequence point between evaluating the n passed to power and the n++ which is passed to printf.
--
Flash Gordon

<Prev in Thread] Current Thread [Next in Thread>
Privacy Policy