Skip to content

Commit 407815c

Browse files
authored
Update variables.c
Fix unprivelaged variable getting that prints bizarre values of variables that haven't been yet assigned. Previously, if you typed 'b' or another variable and pressed enter, it would output some exponential number like 1.23e-142 if you didn't assign that variable before. This fix prevents that by comparing varindex with the index of the current variable VARGET is checking for.
1 parent 933e245 commit 407815c

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

chapter_4/exercise_4_06/variables.c

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -94,24 +94,24 @@ int main(void)
9494
case '~':
9595
push(sin(pop()));
9696
break;
97-
98-
case 'e':
97+
// Be sure to make the commands capitalized not to overlap them with variables, or vice versa according to personal preference
98+
case 'E':
9999
push(exp(pop()));
100100
break;
101101

102-
case 'h':
102+
case 'H':
103103
view_head();
104104
break;
105105

106-
case 'd':
106+
case 'D':
107107
duplicate();
108108
break;
109109

110-
case 's':
110+
case 'S':
111111
swap();
112112
break;
113113

114-
case 'c':
114+
case 'C':
115115
clear();
116116
break;
117117

@@ -121,7 +121,14 @@ int main(void)
121121
break;
122122

123123
case VARGET:
124-
push(var_buff[var - 'a']);
124+
if (var - 'a' <= (varindex - 1)) // Check if the variable has been assigned previously
125+
{
126+
push(var_buff[var - 'a']);
127+
}
128+
else
129+
{
130+
printf("Error: undefined variable.\n");
131+
}
125132
break;
126133

127134
case '\n':
@@ -244,7 +251,7 @@ int getop(char s[])
244251

245252
s[1] = '\0';
246253

247-
if (isalpha(c))
254+
if (isalpha(c) && !isupper(c))
248255
{
249256
var = c;
250257
return VARGET;

0 commit comments

Comments
 (0)