Home > Blockchain >  Boolean value will not change in the main function even though I change it in another function
Boolean value will not change in the main function even though I change it in another function

Time:12-05

I am making a tournament and am using boolean values to say if a team is in or not. If a team loses, then I want that value to be false because they are no longer in the tournament. This is where the problem comes in when I change the value in an if statement and return that value it still stays true even though I told it to be false. I use a printf statement to check the value and both of them are 1 and I want one of them to be 0 because that means the boolean value was changed which is what I want.

I tried using pointers but that didn't work. I honestly just got stuck after that and it finally brought me here.

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

bool generatescore(bool team1, bool team2, char team1name[], char team2name[]) {
    int rand_num1;
    int rand_num2;
    int lower = 25;
    int upper = 100;
    srand(time(NULL));
    rand_num1 = (rand() % (upper - lower 1))   lower;
    rand_num2 = (rand() % (upper - lower 1))   lower;

    int team1_score = rand_num1;
    int team2_score = rand_num2;
    
    printf("%s score: %d\n", team1name, team1_score);
    printf("%s score: %d\n", team2name, team2_score);
    if(team1_score > team2_score) {
        printf("%s made it to the next round\n", team1name);
        team2 = false;
        return team2;
    } else if(team2_score > team1_score) {
        printf("%s made it to the next round\n", team2name);
        team1 = false;
        return team1;
    }
    
    }
    
    
    
int main() {
    bool racoons_status = true;
    bool bulls_status = true;
    bool gators_status = true;
    bool crabs_status =true;
    bool horses_status = true;
    bool worms_status = true;
    bool rats_status = true;
    bool bucks_status = true;

    char racoons[] = "racoons";
    char bulls[] = "bulls";
    char gators[] = "gators";
    char crabs[] = "crabs";
    char horses[] = "horses";
    char worms[] = "worms";
    char rats[] = "rats";
    char bucks[] = "bucks";
    
    generatescore(racoons_status, bulls_status, racoons, bulls);
    printf("%d", racoons_status);
    printf("%d", bulls_status);

    return 0;
}

CodePudding user response:

c passes by value, the bool you get in generatescore is a copy of the one in main, you have to use the 'c style pass by refernce'. Like this

  void myFunc(bool *b){
     *b = false;
   }

   int main(){
      bool b = true;
      myFunc(&b);
   }

ie pass a pointer to the bool in main

  • Related