# Priority checker for infix-to-postfix converter

I am trying to implement an infix to postfix conversion program using stacks. I have actually have done it successfully, but I'm uncertain about the complexity of the logic that I used for the priority checking.

int hasLowerPriority(char ch,char ch2)
{
int num=0,num2=0;
if(ch=='+'||ch=='-')
num=1;
if(ch=='*'||ch=='/')
num=2;
if(ch2=='+'||ch2=='-')
num2=1;
if(ch2=='*'||ch2=='/')
num2=2;
if(num<num2)
return 1;
else
return 0;
}


To keep it simple I am using four basic operators only. I am looking for optimized code for the same operation. Can I reduce its complexity?

## 1 Answer

There is duplicated code that can be removed.

static int precedence(char operator) {
switch (operator) {
case '*': case '/':
return 2;
case '+': case '-':
return 1;
default:
return 0;
}
}

int hasLowerPriority(char operator, char otherOperator) {
return precedence(operator) < precedence(otherOperator);
}


At that point, you might as well get rid of the hasLowerPriority() function altogether, since precedence(operator) < precedence(otherOperator) is clearer and more readable.

(Note that operator is a reserved keyword in C++, but not in C. You might want to rename it to op or something.)

• Thanks I was also thinking about this redundancy. But I forget the great switch statement :) – A.s. Bhullar Jun 25 '14 at 12:08