ayane_m
ayane_m

Reputation: 992

Is it acceptable to initialize temporary strings to keep conditionals readable?

This applies to any language, but for now, let's look at c++. Suppose we have two chars that must take a hexadecimal value:

char b, t;

do {
    //some code

} while(((b<'0' || b>'9') && (b<'A' || b>'F')) || ((t<'0' || t>'9') && (t<'A' || t>'F')));

Phew that last conditional looks scary. Let's look at an alternate:

char b, t;

do {
    //some code

} while(string(1,b).find_first_of("0123456789ABCDEF")==-1 || string(1,t).find_first_of("0123456789ABCDEF")==-1);

The code still looks very messy, but at least we can understand what is going on: a couple of strings are initialized to see if there is a hex character in them.

Assuming there is no difference in performance, is the second solution better than the first one, or is there another way to see if a char contains a hex value without inflating the code?

The chars' case can be changed in the loop to ALLCAPS or lowercase, if necessary (currently ALLCAPS).

Upvotes: 0

Views: 76

Answers (1)

Jesse Good
Jesse Good

Reputation: 52365

I think you are looking for std::isxdigit.

Upvotes: 6

Related Questions