Solved

about ternary operator ?:

Posted on 2004-08-25
4
360 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 50 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 84

Expert Comment

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

Featured Post

ScreenConnect 6.0 Free Trial

At ScreenConnect, partner feedback doesn't fall on deaf ears. We collected partner suggestions off of their virtual wish list and transformed them into one game-changing release: ScreenConnect 6.0. Explore all of the extras and enhancements for yourself!

Question has a verified solution.

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

Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.

820 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