If I want to implement some conditional code that can be implemented in both of the ways. Then which way is better conditional operator ?: or if..then..else??
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It depends. In general, you want the major flow of activity to
be represented in the structure of the code. If the key point
of the algorithm is that the variable
xis initialized, thenthe best solution is to use the conditional operator:
If the decision is the critical issue for understanding what is
going on, then you’ll prefer the
if. In practice, this meansthat when both are reasonably possible, you’ll use
?:. Thekey being “reasonably”—if you find that you’re using the
comma operator in the subexpressions, of the subexpressions have
side effects, then using
?:is probably not “reasonable”.EDIT:
When you do use the
?:operator, in all but the simplestcases, you should format it exactly as you would an
if, e.g.:I do this regularly. (There’s a special case where I’ll push
it: if I can reduce the entire function down to a single return
statement. I still won’t allow side effects of the comma
operator, but I will sometimes use more complicated expressions
than I otherwise would.)