Home > Software engineering >  Problem while using multiple conditions in a 'while loop'
Problem while using multiple conditions in a 'while loop'

Time:07-29

So, I'm just starting to learn the C language and coding in general. I was learning about 'while loops' in C and came across this problem while making a guessing game (idea from the internet). Here's the code:

    #include<stdio.h>
#include<stdlib.h>


int main(){
    int answer = 10;
    int guess[2];
    int i = 0;
    int remaningGuesses = 3;
    while(guess[i-1] != answer && remaningGuesses != 0){
        printf("Remaining guesses %d.Enter a number: ", remaningGuesses);
        scanf("%d", &guess[i]);
        i  ;
        remaningGuesses = remaningGuesses - 1;
    }
        printf("%d\n", i);
   
    printf("%d\n", guess[i-1]);
    printf("%d\n", answer);     
       
    /*alright i see the problem now. the value of 'answer' changes to 'guess[i-1]', though i don't know y.*/
    
    if(guess[i-1] = answer){
        printf("Your answer is right");
    }else{
        printf("Your answer is wrong");
    }
    return 0;
}

After much time I discovered that the value of 'answer' was changing to 'guess[i-1]'. What I don't understand is, how it could be happening. Any kind of help will be appreciated.

Though I suspect it was got something to do with the multiple conditions in the condition part of the 'while loop'.

CodePudding user response:

You are invoking undefined behaviour.

For an array with 2 elements you may access elements with index 0 or 1. Your loop starts with index -1. This is an out of bounds access causing undefined behaivour. This is not at all related to using multiple subexpressions in your condition.

Second error is that you store up to 3 guesses but only provide memory for 2 values in your array.

Third error: You compare the guess with the answer already before you even tried to read the first guess. In case you accidentally access answer via illegal array index, this would cause the loop to exit already before first iteration as it actually compares answer != answer which is false.

  • Related