Home > Software engineering >  Evaluating a postfix expression
Evaluating a postfix expression

Time:02-11

This is a program to evaluate a post-fix expression using stack. Why in the 8th line we have pushed question[i]-'0' rather than just question[i]. I did not understand the role of 0.

stack<int> s;
int main(){
  string question;
  cin>>question;

  for(int i = 0 ; i < question.length() ; i  ){
    if(isdigit(question[i]))
      s.push(question[i] - '0');
    else{
      int a = s.top();
      s.pop();
      int b = s.top();
      s.pop();

      if(question[i]==' ') s.push(a b);
      else if(question[i]=='-') s.push(a-b);
      else if(question[i]=='*') s.push(a*b);
      else if(question[i]=='/') s.push(a/b);
    }
  }
  cout<<"Converting to infix and solving we get : "<<s.top();
  return 0;
}

CodePudding user response:

'0' is a character literal.

So when you wrote:

s.push(question[i] - '0');

The fundamental reason why/how question[i] - '0' works is through promotion. In particular,

both question[i] and '0' will be promoted to int. And the final result that is pushed onto the stack named s will be the result of subtraction of those two promoted int values.

Also note that the C Standard (2.3 Character sets) guarantees that:

  1. ...In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

For example, say we have:

std::string question = "123";
int a = question[0] - '0'; //the result of question[0] - '0' is guaranteed to be the integer 1
int b = question[1] - '0'; //the result of question[1] - '0' is guaranteed to be the integer 2
int c = question[2] - '0'; //the result of question[2] - '0' is guaranteed to be the integer 3

Lets consider the statement int a = question[0] - '0';:

Here both question[0] and 0 will be promoted to int. And the final result that is used to initialize variable a on the left hand side will be the result of subtraction of those two promoted int values on the right hand side. Moreover, the result is guaranteed to be the integer 1.

Similarly, for statement int b = question[1] - '0';:

Here both question[1] and 0 will be promoted to int. And the final result that is used to initialize variable b on the left hand side will be the result of subtraction of those two promoted int values on the right hand side. Moreover, the result is guaranteed to be the integer 2.

And similarly for variable c.

  •  Tags:  
  • c
  • Related