Skip to main content
1 of 2
pacmaninbw
  • 24.9k
  • 11
  • 46
  • 109

Typo or Bug
Any time a array of characters is to be used as a string the length of the array MUST be 1 + the expected length of the string to allow for the NULL value that terminates the string.

char blank[1] = "-";

Code such as line 23 above can cause the program to either terminate abnormally or cause all kinds of interesting problems.

Global Variables
Some people say global variables are evil and never use them, they are not quite correct, but in this case there are multiple ways around using global variables. Some of the functions could return values rather than void, variables can be passed into some functions by either by value or by reference.

Pass By Value means that a copy of the variable is used within the function and any changes made to the variable within the function won't change the value in the rest of the program. Pass By Reference means that the address of the variable is passed into the function and any changes made to the variable will change in the rest of the program. In C the contents of an array all always pass by reference because an array is a memory address.

Global variables make programs much harder to debug because it is hard to find where the variable is changed within the program, this is true even when the program is a single file such as this one, but with multiple source files it is much harder.

If you declared any of these global variable in multiple files the linking phase would report multiple definitions and then quit. If a variable needs to be global within a single file and not elsewhere it should be declared as a static variable.

It is best to limit the scope of a variable to just where it is needed. If a variable is only used in a for loop, declare it in that for loop. The variable random_number should be declared in the get_word() function because it is only referenced in that function.

It would be best if get_word returned a character array rather than setting a global variable.

Complexity
There is a good start on creating functions in the program, but main() is still too complex. In large programs main is used to set up for processing, call the processing function(s) and clean up. It might be a good practice to always limit the code in main() to this functionality. Perhaps a function called run_game() could contain most of the code in main() including the call to start_game().

Performance
The program might be faster if it read all the strings into an array of strings (char **words). The random number can then be used as an index into the array of strings rather than rereading some or all of the file. Multiple passes through a file are time consuming and should be avoided when possible. The functions fopen(), fclose(), fgets() and rewind() are all system calls and cause the program to be swapped out when they are called.

pacmaninbw
  • 24.9k
  • 11
  • 46
  • 109