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

Re: Implementation-defined behaviour

Subject: Re: Implementation-defined behaviour
From: Ioannis Vranos
Date: Sat, 29 Mar 2008 22:16:27 +0200
Newsgroups: comp.lang.c

Herbert Rosenau wrote:
> On Fri, 28 Mar 2008 17:37:46 UTC, Ben Bacarisse <ben.usenet@xxxxxxxxx>
> wrote:
> 
>> Ioannis Vranos <ivranos@xxxxxxxxxxxxxxxxxxxxxxxxx> writes:
>>
>>> Dann Corbit wrote:
>>>> --- Module:   foo.c (C)
>>>>                             _
>>>>     printf("%d %d\n", n++, n);
>>>> foo.c(8) : Warning 564: variable 'n' depends on order of evaluation
>>> I wonder a bit about this one. Let's consider a simpler version:
>>>
>>>
>>> #include <stdio.h>
>>>
>>> int somefunc(int x)
>>> {
>>>     printf("%d\n", x);
>>>     return x;
>>> }
>>>
>>> int main(void)
>>> {
>>>     int x= 1;
>>>     somefunc(x++);  
>>>     return 0;
>>> }
>>>
>>> Above, is it well defined that it will be printed "1"?
>> Yes, all well-defined as far as I can see.  What might be the problem?
>>
>>> #include <stdio.h>
>>>
>>> int somefunc(int x)
>>> {
>>>     printf("%d\n", x);
>>>     return x;
>>> }
>>>
>>> int main(void)
>>> {
>>>     int x= 1;
>>>     somefunc( (x++, somefunc(x)) ); 
>>>     return 0;
>>> }
>>>
>>> In the above, the expression (x++, somefunc(x)) is evaluated to 2, so I
>>> assume it is guaranteed that it will print "2".
> 
> No, It gives undefined behavior.
>  
>> Well, it will print "2" twice since there are two calls, but again,
>> all well-defined.  The comma operator has a sequence point between its
>> two parts so x can be used safely in the right-hard part.
>>
> No, it is undefined because the sequence the parameters are evulated 
> is simply undefined, so it is not defined when x++ will be evaluated. 
> It is open to the implementation when the ++ will be done. No, the 
> comma here is not the comma operator but only a separator. There is no
> sequence point between the arguments to somefunc.


In the somefunc( (x++, somefunc(x)) );  call, we have one argument:

( x++, somefunc(x) )

which is evaluated from left to right, with value the return value of
somefunc(x) which in this case is 2.


Consider another example:


int x= 1;

/* The external parentheses are not needed */
(x++, printf("%d\n", x));


The above will print 2.


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