The Print Statement

This page last updated: Sunday September 27, 1998 01:07

Program Grammar #2 has a print statement with arguments:

print := TT_PRINT expr ( ',' expr ) *

This file describes the print statement and gives examples of its output.

The Print statement is a statement that starts with the keyword print. The print keyword is a reserved word in the grammar that is matched by the scanner and returned as the TT_PRINT token type.  (Select here to learn how to implement reserved words.)

The semantic meaning of the print statement is to print the value of its argument(s) on the parser's output stream, without extra blanks, commas, or extra newlines, e.g.:

print "Hello World!\n";
Hello World!

print "Look!\nMultiple lines!\n\nJust the way C would do it!\n";
Look!
Multiple lines!

Just the way C would do it!

print "1 + 5 * 3 is ", 1+5*3, ", which isn't a big number.\n";
1 + 5 + 3 is 16, which isn't a big number.

print "The value of 1000 times (30+1) is ", 1000*(30+1), "...\n";
The value of 1000 times (30+1) is 31000...

print "The value of 1000 times 1000 is ", 1000*1000, ".\n";
The value of 1000 times 1000 is 1000000.

print "Note how we print \"quoted\" strings properly. It's good\n";
Note how we print "quoted" strings properly. It's good.

print "What happens when you add a number to a string?" + 32767;
File ian.txt Line 1: Non-numeric operand(s):
   String 'What happens when you add a number to a string?' and/or
   Unsigned Integer '32767'
File ian.txt Line 1: Skipped to Semicolon ';'

Each argument to print (each expression) is popped from the value stack and printed correctly according to its type. No punctuation or blanks are added. Numbers print as numbers; strings print as strings.

The grammar production for the print command annotated with semantic action symbols shows how it works:

print := TT_PRINT expr {pop;print} ( ',' expr {pop;print} ) *

The expression parser handles type checking and expression parsing errors and pushes the value of each expression on the value stack.  The print command merely loops, calling the expression parser and popping each comma-separated expression off the value stack and printing it according to its type.  The item_value() utility function is useful here.

Do not add extra blanks or newlines to the output of the print command.  Print only the arguments, exactly as given.