comma before ?:

F

Fraser Ross

int
a= 4,
c= 0,
x= 100,
y= 200;
c ? ++a, x : y ; // comma before ?:

Should a be 5 at the end? If this is not an example of comma precedence
over ?: can someone give one?

Fraser.
 
R

Ron Natalie

Fraser said:
int
a= 4,
c= 0,
x= 100,
y= 200;
c ? ++a, x : y ; // comma before ?:

Should a be 5 at the end? If this is not an example of comma precedence
over ?: can someone give one?
First off, anybody who uses ?: and discards the value should
have their fingers broken. That's what if/else is for.
C++ parsing is not strictly determined by operator precedence,
the ? operator is a pretty good examle of that.

The question isn't one of precedence anyhow. Precedence doesn't
change the order and when things are executed, just how they are
parsed. If c is false, the stuff before the colon is NOT evaluated
and no side-effects occur.
 
V

Victor Bazarov

Fraser said:
int
a= 4,
c= 0,
x= 100,
y= 200;
c ? ++a, x : y ; // comma before ?:

Should a be 5 at the end?
No.

If this is not an example of comma
precedence over ?: can someone give one?

It *is* an example of comma precedence over ?:. The last line
is interpreted as if it were written

c ? (++a, x) : y ;

HOWEVER, since 'c' is 0, the parenthesised (here) expression is
not evaluated. 'a' will be 4. Change 'c' to be initialised with
non-zero value, and 'a' will get incremented.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,754
Messages
2,569,527
Members
44,999
Latest member
MakersCBDGummiesReview

Latest Threads

Top