C: "?:" operator expression equivalency -
a few days ago wrote function that'd receive int n greater 0 , return nth prime number. wondered how shorter wrote , came 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 saw n%d<1 in , thought why not change n%d , invert order of "?:" operator expressions, 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 doesn't work, gets stuck in infinite loop. d=2 never happens, think. can point me out why not or read figure out?
if it's of help, i'm running ubuntu , compiling gcc -std=c99 only.
it's issue of operator precedence. ?: has higher precedence ,, so
a , b ? c : d , e parses as
a , (b ? c : d) , e however, doesn't apply middle part of ?: works it's surrounded parens (because in sense ? ... : bracketing construct):
a ? b , c : d parses as
a ? (b , c) : d because that's thing can without being syntax error.
you can fix adding explicit parens:
n%d?d++:(n++,d=2);
Comments
Post a Comment