Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shorthand c++ if else statement

Tags:

So I'm just curious if there is a short hand statement to this:

if(number < 0 )   bigInt.sign = 0; else   bigInt.sign = 1; 

I see all these short hand statements for if a < b and such.

I'm not sure on how to do it properly and would like some input on this.

Thanks!

I actually just figured it out right before you guys had answered.

The shortest solution is bigInt.sign = (number < 0) ? 0 : 1

like image 402
kevorski Avatar asked Jul 17 '14 02:07

kevorski


People also ask

Which is shorthand of if-else statement?

The ternary operator, also known as the conditional operator, is used as shorthand for an if...else statement. A ternary operator is written with the syntax of a question mark ( ? ) followed by a colon ( : ), as demonstrated below. In the above statement, the condition is written first, followed by a ? .

Does C have an else if?

C has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.

Can IF statement have 2 conditions in C?

There can also be multiple conditions like in C if x occurs then execute p, else if condition y occurs execute q, else execute r. This condition of C else-if is one of the many ways of importing multiple conditions.

What is the conditional operator in C?

The conditional operator is a single programming statement and can only perform one operation. The if-else statement is a block statement, you can group multiple statements using a parenthesis. The conditional operator can return a value and so can be used for performing assignment operations.


1 Answers

The basic syntax for using ternary operator is like this:

(condition) ? (if_true) : (if_false) 

For you case it is like this:

number < 0 ? bigInt.sign = 0 : bigInt.sign = 1; 
like image 191
Bla... Avatar answered Oct 16 '22 09:10

Bla...