From 115b8f8132f1025f2cd1a2d7b7d9a62635c67e0c Mon Sep 17 00:00:00 2001 From: Tibor Bizjak Date: Sun, 9 Jul 2023 19:30:05 +0200 Subject: [PATCH] added print variables command --- k&r/04-funcs-and-prog-struct/04-calc.c | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/k&r/04-funcs-and-prog-struct/04-calc.c b/k&r/04-funcs-and-prog-struct/04-calc.c index 80e6f31..c290c25 100644 --- a/k&r/04-funcs-and-prog-struct/04-calc.c +++ b/k&r/04-funcs-and-prog-struct/04-calc.c @@ -69,10 +69,13 @@ double lst_print; char var_flags[NS_SIZE]; double var_vals[NS_SIZE]; +/* is_var: return 0 if c is not a variable name */ +#define is_var(c) isalpha(c) + /* set_var: pop val from stack, set variable c to val */ #define set_var(c) \ do { \ - int i = c - 'a'; \ + int i = tolower(c) - 'a'; \ var_flags[i] = 1; \ var_vals[i] = pop(); \ } while (0) @@ -80,13 +83,21 @@ double var_vals[NS_SIZE]; /* get_var: push value of c to stack */ #define get_var(c) \ do { \ - int i = c - 'a'; \ + int i = tolower(c) - 'a'; \ if (!var_flags[i]) \ printerr(VAR_NOT_SET_ERR, i+'a'); \ else \ push(var_vals[i]); \ } while (0) +/* print_vars: print all set variables and their values */ +void print_vars(void) +{ + int i; + for (i = 0; i < NS_SIZE; i++) + if (var_flags[i]) + printf("%c = %.8g\n", i+'a', var_vals[i]); +} /* --------- CALCULATOR FUNCTION TYPES */ /* the following macros allow us to call native c constructs @@ -132,6 +143,7 @@ double var_vals[NS_SIZE]; X(swap, "swap top two elements of stack", COMMAND) \ X(clear, "clear stack", COMMAND) \ X(help, "print all available commands", COMMAND) \ + X(vars, "print defined variables and their values", CALL, print_vars, COMMAND) #define OPERATORS \ X(+, "add operands", COMM_OP) \ @@ -204,8 +216,8 @@ int main() TOKENS #undef X #define X(C, DESC, F) \ - if (t_len == 2 && token[0] == C && isalpha(token[1])) \ - F(tolower(token[1])); \ + if (t_len == 2 && token[0] == C && is_var(token[1])) \ + F(token[1]); \ else VAR_TOKENS #undef X