user9319233
user9319233

Reputation:

Is it possible to shorten this if statement?

I simply want to know if I can make whats in the parenthesis of this if statement simpler.

if (augend[i]=='0' && partialSum[i]=='0' && carry=='0')

Such as (augend[i] & partialsum[i] & carry == '0'). I'm still learning so i'm not quite sure if something like this is possible.

Upvotes: 0

Views: 157

Answers (7)

Joseph Franciscus
Joseph Franciscus

Reputation: 371

Encapsulation:

bool zeros() {
    return true;
}
template<class... chars>
bool zeros(char x, chars... lst) {
    return x == '0' && zeros(lst...);
}
if (zeros(augend[i], partialSum[i], carry)){
     //impl//
}   

 //lined up just for size comparison
if (augend[i]=='0' && partialSum[i]=='0' && carry=='0')
if (zeros(augend[i], partialSum[i], carry))

This is more brief and becomes much much shorter the more parameters you have to compare (as you don't need to write =='0' each time).


If you need it for any char....

bool equal(char match) {
   return true;
}
template<class... chars>
bool equal(char match, char front, chars... lst) {
    return match == front && equal(match, lst...);
}

Upvotes: 1

Walter
Walter

Reputation: 45414

  1. No, the numerical value for '0' is not 0, but usually 48 (but that is not portable), so your bitwise trick will not work.

  2. Even if bitwise tricks would be possible, don't do that. Leave the code as is, for it is clear and easy to understand.

What you're attempting to do is premature micro-optimization and ultimately a bad idea.

Upvotes: 4

MO1988
MO1988

Reputation: 57

if (augend[i]==partialSum[i]==carry=='0')

or

(augend[i]==partialSum[i]==carry=='0') ? (if_true) : (if_false)

Upvotes: -1

aschepler
aschepler

Reputation: 72271

You could do

if(!(augend[i]^'0'|partialSum[i]^'0'|carry^'0'))

This is an excellent way to make readers of your code, including probably future you, wonder what the *$#@ is going on.

In case the sarcasm wasn't clear, please DON'T actually do this. (Unless this is for a "code golf" competition, in which case there would be a number of other things you could probably improve.) Your original code is much better.

Upvotes: 0

Abhishek Kumar
Abhishek Kumar

Reputation: 307

you can do this:

if(augend[i]=='0' & partialSum[i]=='0' & carry=='0'){}

as == has greater precedence and will return bool on which bitwise operator can be used.

Upvotes: 0

pm100
pm100

Reputation: 50110

if these were ints rather than characters (ie carry == 0 is what you want) then you could do

if (!augend[i] && !partialSum[i] && !carry)

Since we dont know what you are doing its hard to say. But if (carry) and if(!carry) feel quite natural if you are doing some kind or arithmetic.

Upvotes: 0

grit
grit

Reputation: 93

Nope, that's as short it can be

Upvotes: 0

Related Questions