? :

B

Bill Cunningham

Please someone correct me if I'm wrong but I understand ? and : to be
like this:

if (a<b) {};

Long way.

(a<b) ?/*dothis*/ : /*do that*/

Is this what the ? and : means? If not can someone so me a simple example?

Sincerely
Bill
 
I

Ian Collins

Bill said:
Please someone correct me if I'm wrong but I understand ? and : to be
like this:

if (a<b) {};

Long way.

(a<b) ?/*dothis*/ : /*do that*/

Is this what the ? and : means? If not can someone so me a simple example?

4/10, getting better.
 
L

Lew Pitcher

Please someone correct me if I'm wrong but I understand ? and : to be
like this:

if (a<b) {};

Long way.

(a<b) ?/*dothis*/ : /*do that*/

Is this what the ? and : means?

No. The ternary operator isn't a statement selection entity, it is a /value/
selection entity. You can't seed the ternary operator's "true"
and/or "false" branches with statements that do not result in an value.
If not can someone so me a simple example?

The statement

a = (b < 0 ? 10 : 20);

is equivalent to

if (b < 0)
a = 10;
else
a = 20;

But, the statement
b < 0 ? return 4: while (1) {putchar(' ');};
is a syntax error (neither "return 4" nor "while (1) {}" are values).

The ternary operator (as it is called) consists of three parts:
1) a condition,
2) a value to be used when the condition is true, and
3) a value to be used when the condition is false.

The operator resolves to a single value, one of the two values given in it's
body. /Which/ value depends on the results of the condition.


--
Lew Pitcher

Master Codewright & JOAT-in-training | Registered Linux User #112576
http://pitcher.digitalfreehold.ca/ | GPG public key available by request
---------- Slackware - Because I know what I'm doing. ------
 
R

Richard

Bill Cunningham said:
Please someone correct me if I'm wrong but I understand ? and : to be
like this:

if (a<b) {};

Long way.

(a<b) ?/*dothis*/ : /*do that*/

Is this what the ? and : means? If not can someone so me a simple example?

Sincerely
Bill

1/10
 
B

Bill Cunningham

Long way:

if (a<b) {
c = a;
} else {
c = b;
}


Short way:

c = (a<b ? a : b);
So this is only used then if you want to conditionally assign values ?

Bill
 

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

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top