Is there a way to shorten this while condition?

Lukáš Pištěk picture Lukáš Pištěk · Jul 23, 2019 · Viewed 7.1k times · Source
while (temp->left->oper == '+' || 
       temp->left->oper == '-' || 
       temp->left->oper == '*' || 
       temp->left->oper == '/' || 
       temp->right->oper == '+' || 
       temp->right->oper == '-' || 
       temp->right->oper == '*' || 
       temp->right->oper == '/')
{
    // do something
}

For clarity: temp is a pointer that points to following node structure:

struct node
{
    int num;
    char oper;
    node* left;
    node* right;
};

Answer

paddy picture paddy · Jul 23, 2019

Sure, you could just use a string of valid operators and search it.

#include <cstring>

// : :

const char* ops = "+-*/";
while(strchr(ops, temp->left->oper) || strchr(ops, temp->right->oper))
{
     // do something
}

If you are concerned about performance, then maybe table lookups:

#include <climits>

// : :

// Start with a table initialized to all zeroes.
char is_op[1 << CHAR_BIT] = {0};

// Build the table any way you please.  This way using a string is handy.
const char* ops = "+-*/";
for (const char* op = ops; *op; op++) is_op[*op] = 1;

// Then tests require no searching
while(is_op[temp->left->oper] || is_op[temp->right->oper])
{
     // do something
}