c - Incrementing an integer and initialisation placement having a weird effect? -
i have written following 'hangman game'-program in c (was written quick , dirty don't mind code much):
#include <stdio.h> int main() { char word[] = "cat"; int amountguessesallowed = 5; size_t size = sizeof(word)-1; // -1 exclude '\0' char guessedword[size]; (int i=0; i<size; i++){ guessedword[i] = '_'; } int lettersguessed = 0; int totaltimesguessed = 0; char c; printf("%s\n", guessedword); printf("guess %d - enter character: ", totaltimesguessed+1); scanf("%s", &c); while (totaltimesguessed < amountguessesallowed) { for(int i=0; i<size; i++){ if (word[i] == c && guessedword[i] == '_'){ printf("it matches character @ index %d!\n", i); guessedword[i] = c; lettersguessed++; printf("letters guessed: %d\n", lettersguessed); } } totaltimesguessed++; if (lettersguessed == size) { printf("you win!"); return 0; } else if (totaltimesguessed == amountguessesallowed) { printf("you lose!"); return 0; } else { printf("%s\n", guessedword); printf("guess %d - enter character: ", totaltimesguessed+1); scanf("%s", &c); } } }
the issue appears 3 initialisation lines of lettersguessed, totaltimesguessed , c.
if execute program , enter couple of letters you'll notice reason totaltimesguessed
-value appears 2
, no longer appears incrementing. there don't appear problems lettersguessed
-variable.
___ guess 1 - enter character: b ___ guess 2 - enter character: c matches character @ index 0! letters guessed: 1 c__ guess 2 - enter character: j c__ guess 2 - enter character:
now if swap order of lettersguessed
, totaltimesguessed
lettersguessed
-variable having issue (remains 1)!
___ guess 1 - enter character: c matches character @ index 0! letters guessed: 1 c__ guess 2 - enter character: matches character @ index 1! letters guessed: 1 ca_ guess 3 - enter character:
finally, if place char c;
line before 2 ints:
char c; int lettersguessed = 0; int totaltimesguessed = 0;
then works expected!
___ guess 1 - enter character: c matches character @ index 0! letters guessed: 1 c__ guess 2 - enter character: matches character @ index 1! letters guessed: 2 ca_ guess 3 - enter character:
i've tested in xcode gcc.
there must logical explanation this? hunger enlightenment!
you causing undefined behavior in
scanf("%s", &c);
because "%s"
specifier adds terminating nul
byte target single char
.
instead can try
if (scanf(" %c", &c) != 1) handleerrorplease();
the space before "%c"
intentional, eat white space character left previous call scanf
.
when undefined behavior occurs, it's layout of program in when it's loaded memory happen, hence changing order of defined variables causes behavior different.
Comments
Post a Comment