Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Integer ops, associativity and precedence...

3 views
Skip to first unread message

gwowen

unread,
Dec 16, 2009, 3:21:44 AM12/16/09
to
Is the following function well defined?

int f(int a, int b int c){
return a * b / c;
}

If so, what is f(5,1,3) ?

Richard Heathfield

unread,
Dec 16, 2009, 3:39:34 AM12/16/09
to
In
<f708f4e9-3676-4f3d...@f20g2000vbl.googlegroups.com>,
gwowen wrote:

> Is the following function well defined?

In general, yes, but not if overflow occurs (undefined) or c is 0
(undefined) or if either operand is negative
(implementation-defined).

>
> int f(int a, int b int c){
> return a * b / c;
> }
>
> If so, what is f(5,1,3) ?

5 * 1 / 3 is equivalent to (5 * 1) / 3, which is equal to 5/3 = 1,
because multiplication and division (which have the same precedence)
associate left-to-right.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within

gwowen

unread,
Dec 16, 2009, 3:39:04 AM12/16/09
to
On Dec 16, 8:39 am, Richard Heathfield <r...@see.sig.invalid> wrote:

> 5 * 1 / 3 is equivalent to (5 * 1) / 3, which is equal to 5/3 = 1,
> because multiplication and division (which have the same precedence)
> associate left-to-right.

Thank you. Every compiler I used said that, but I couldn't find the
"associate left-to-right" bit in t'standard.

Richard Heathfield

unread,
Dec 16, 2009, 3:49:04 AM12/16/09
to
In <5b1e84a4-c7b2-4230...@1g2000vbm.googlegroups.com>,
gwowen wrote:

That's because associativity isn't spelled out explicitly in the
Standard; it's implicit in the grammar, and is given only the
briefest of passing mentions in the text.

Eric Sosman

unread,
Dec 16, 2009, 7:59:04 AM12/16/09
to
On 12/16/2009 3:21 AM, gwowen wrote:
> Is the following function well defined?
>
> int f(int a, int b int c){
> return a * b / c;
> }

No, it's a syntax error.

> If so, what is f(5,1,3) ?

A function call. To a function for which no valid
definition has been exhibited.

--
Eric Sosman
eso...@ieee-dot-org.invalid

robert...@yahoo.com

unread,
Dec 16, 2009, 6:43:23 PM12/16/09
to
On Dec 16, 2:39 am, Richard Heathfield <r...@see.sig.invalid> wrote:
> In
> <f708f4e9-3676-4f3d-a585-1f0e9dcd2...@f20g2000vbl.googlegroups.com>,

>
> gwowen wrote:
> > Is the following function well defined?
>
> In general, yes, but not if overflow occurs (undefined) or c is 0
> (undefined) or if either operand is negative
> (implementation-defined).


Since I'm in a nit-picky mood...

The last is true only in C89/90, and only if the result is not exactly
an integer. C99 specifies the behavior.

0 new messages