Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

about ternary operator ?:

Posted on 2004-08-25
4
Medium Priority
?
364 Views
Last Modified: 2012-06-27
hello experts.
please tell me how do i write the following using ternary operator :
if(a>b)
{
  x=10;
}
else
{
  y=20;
}

there is no printf involved.

thanks.
0
Comment
Question by:astudent
  • 2
4 Comments
 
LVL 45

Accepted Solution

by:
sunnycoder earned 150 total points
ID: 11899771
Hi astudent,

(a>b)?x=10:y=20;

Sunnycoder
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 11899780
the basic idea is

if (condition) gets shortened to
(condition)

this is followed by a '?' symbol ... so we have (condition)?

next comes the statement to execute if the condition is true

(condition)?<if_true_statement>

next a ':' symbol followed by the statement to execute if the condition was false (the else part)

(condition)?<if_true_condition>:<if_flase_condition>
0
 
LVL 55

Expert Comment

by:Jaime Olivares
ID: 11902697
Although the ternary operator will work for your needs, it is not a good practice to assign values to different variables. This is a more usual case:

if(a>b)
  x=10;
else
  x=20;

Could be:

x= (a>b) ? 10 : 20

0
 
LVL 85

Expert Comment

by:ozo
ID: 11905093
(a>b)?x=10:(y=20);
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
Suggested Courses

824 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question