{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Chapter 6

# Analogy a group of people can deal with a complex

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: by each person handling only problems in his/her own specialty, leaving the rest for colleagues. Stroustrup/Programming 16 Function Return Types Function What should the parser functions return? What How about the result? Token get(); // read characters and compose tokens read double expression(); // deal with + and – deal // return the sum (or difference) return double term (); // deal with *, /, and % deal // return the product (or …) return double primary(); // deal with numbers and parentheses deal // return the value What is a Token? What Token Stroustrup/Programming 17 number 4.5 What is a token? What + We want to see input as a stream of tokens We read characters 1 + 4*(4.5-6) (That’s 13 characters incl. 2 spaces) (That’s 9 tokens in that expression: 1 + 4 * ( 4.5 - 6 ) tokens 4.5 6 kinds of tokens in that expression: number +*(-) kinds We want each token to have two parts A “kind”; e.g., number A value; e.g., 4 value; We need a type to represent this “Token” idea We’ll build that in the next lecture, but for now: get_token() gives us the next token from input t.kind gives us the kind of the token t.value gives us the value of the token Stroustrup/Programming 18 Dealing with + and Dealing Expression: Term Expression ‘+’ Term Expression ‘-’ Term // Note: every Expression starts with a Term // Note: double expression() // read and evaluate: 1 1+2.5 1+2+3.14 etc. // read { double left = term(); // get the Term double get while (true) { Token t = get_token(); // get the next token… // get switch (t.kind) { // … and do the right thing with it // and case '+': left += term(); break; case '-': left -= term(); break; default: return left; // return the value of the expression return // return } } Stroustrup/Programming 19 } Dealing with *, /, and % Dealing double term() // exactly like expression(), but for *, /, and % // exactly { double left = primary(); // get the Primary double get while (true) { Token t = get_token(); // get the next Token… // get switch (t.kind) { case '*': left *= primary(); break; case '/': left /= primary(); break; case '%': left %= primary(); break; default: return left; // return the value return // return } } } Oops: doesn’t compile % isn’t defined for floating-point numbers Stroustrup/Programming 20 Dealing with * and / Dealing Term : Primary Term ‘*’ Primary Term Term ‘/’ Primary // Note: every Term starts with a Primary Note: double term() // exactly like expression(), but for *, and / // exactly { double left = primary(); // get the Primary double get while (true) { Token t = get_token(); // get the next Token // get switch (t.kind) { case '*': left *= primary();...
View Full Document

{[ snackBarMessage ]}