Solved

about ternary operator ?:

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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

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…
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
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 how to create, access, and change arrays in the C programming language.

759 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

20 Experts available now in Live!

Get 1:1 Help Now