Solved

about ternary operator ?:

Posted on 2004-08-25
4
356 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

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

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

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…
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…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.

864 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now