Parsing Simple Assignment Statements in PASCAL
The task involves interpreting a sequence of PASCAL assignment statements for three variables: a, b, and c. Each statement follows the pattern [variable]:=[variable or single-digit integer];. All variables are initialized to 0. The sattements must be executed in order, and the final values of a, b, and c must be output.
Approach
- Initialize an array to hold the values for
a,b, andc, all set to 0. - Process the input string sequentially to identify each assignment operation.
- For each assignment, deetrmine the target variable (lvalue) and the source value (rvalue). The rvalue can be a single-digit constant (0-9) or one of the three variables.
- Update the target variable's value based on the rvalue.
- After processing all statements, print the final values.
Implementation Details
The core logic scans the input string for the assignment operator (=). When found, it examines the character immediate following the = to decide the assignment type.
- If it's a digit, the numeric value is assigned direct.
- If it's a letter, the value is copied from the corresponding variable's current storage.
The index for the target variable is derived from the character two positions before the = (accounting for the colon :). ASCII arithmetic converts characters to array indices.
Code Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string code;
int varValues[3] = {0}; // Index 0: a, 1: b, 2: c
cin >> code;
for (size_t pos = 0; pos < code.length(); ++pos) {
if (code[pos] == '=') {
char targetVar = code[pos - 2]; // Variable before ':'
char source = code[pos + 1]; // Character after '='
if (source >= '0' && source <= '9') {
// Assign numeric literal
varValues[targetVar - 'a'] = source - '0';
} else {
// Copy value from another variable
varValues[targetVar - 'a'] = varValues[source - 'a'];
}
}
}
cout << varValues[0] << " " << varValues[1] << " " << varValues[2] << endl;
return 0;
}