CrossNox
CrossNox

Reputation: 53

C: "?:" operator expression equivalency

A few days ago i wrote a function that'd receive an int n greater than 0 and return the nth prime number. I wondered how much shorter that could be wrote and i came up with this:

int f(int i){int n=2,d=2,j=1;for(j;j<i;j+=n==d)n%d<1?n++,d=2:d++;return n;}

Then i saw the n%d<1 in the for and thought why not change it with just n%d and invert the order of the "?:" operator expressions, like this:

int g(int i){int n=2,d=2,j=1;for(j;j<i;j+=n==d)n%d?d++:n++,d=2;return n;}

But it just doesn't work, it gets stuck in an infinite loop. The d=2 never actually happens, i think. Can anyone point me out why not or what to read to figure it out?

If it's of any help, i'm running Ubuntu and compiling with gcc -std=c99 only.

Upvotes: 1

Views: 95

Answers (2)

melpomene
melpomene

Reputation: 85887

It's an issue of operator precedence. ?: has higher precedence than ,, so

A , B ? C : D , E

parses as

A , (B ? C : D) , E

However, this doesn't apply to the middle part of ?: which works like it's surrounded by parens (because in a sense ? ... : is a bracketing construct):

A ? B , C : D

parses as

A ? (B , C) : D

because that's the only thing it can do without being a syntax error.


You can fix this by adding explicit parens:

n%d?d++:(n++,d=2);

Upvotes: 3

Ilmari Karonen
Ilmari Karonen

Reputation: 50378

The ternary ?: operator has higher precedence than the comma. Thus,

n%d?d++:n++,d=2

gets parsed as:

(n % d ? d++ : n++), d = 2

which is not what you want.

The reason it works in your first example is because there the comma is between the ? and the :, which act as paired delimiters just like parentheses, curly braces and square brackets do.

Upvotes: 2

Related Questions