Hi guys

I have part of the code that looks something like this:

    	  else if(c1=='b')
    	  else if(c1=='c')

I just want to ask is there any way to rewrite this code, to make it more compact
something like

if(c1==('(a'||'b'||'c') // I know this doesn't work

but I'm looking something that would be nice and short.

6 Years
Discussion Span
Last Post by shean1488

You can OR the expressions together like this
c1=='a' || c1 == 'b' ...

but if you want a very short version with many tests like that you can use some geeky construct like
"abc".indexOf(c1) >= 0


you were close tho, you can use "||" which is OR , "|" would work too but "||" is more efficient, because if the first condition is true then it knows it makes no diference to check the second, where you got it wrong is you gotta give full conditions on each side of the OR, so :

if(c1=='a' || c1=='b' || c1=='c')myStack.push(c1);

if you had to execute diferent code in each "else if" of the orginal code, you could still compact it with ternary operators "(condition?truestatement:falsestatement);"

like this :

(c1=='a' ? myStack.push(c1) : (c1=='b' ? myOtherStack.push(c1) : (c1=='c' ? myThirdStack.push(c1) : "" ) ) );

please note that im not entirely sure about the "" part where it doesnt meet any requirement, i believe ternary operators will ask for each of its outcomes to return the same type of value, so whatever push returns you would need to return that , in case of a bool , put false instead of ""... etc.

but that was just a little extra anyways ;P enjoy

Edited by Philippe.Lahaie: typos

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.