why the bool value doesnt modified by void function?

#include <stdio.h>
#include <stdbool.h>
#include "header.h"

int main() {
    bool check = true;
    while (check) {
        test(check);
        //printf("%d", check);
    }
    return 0;
}

this is my main.c file

and this is my header.c file

#include <stdbool.h>
void test(bool check)
{
    while (true)
    {
                if(check){
        check = false;
        break;
                }
    }
}

i notice this while im doing the another programm , and it goes inifite loop.
why the check value doesnt change to false?

get a false value and end loop

>Solution :

C is pass-by-value, not by-reference.

This means that test() gets a copy of the value of the check variable’s value. It has no way to reach back and change the caller’s variable, that the argument is named the same as the variable does not matter.

To fix it, you need to pass the address of the value instead, using pointers:

void test(bool *check)
{
    while (true)
    {
        if (*check){
            *check = false;
            break;
        }
    }
}

and then of course you need to explicitly pass the address, in main():

int main() {
    bool check = true;
    while (check) {
        test(&check);
        //printf("%d", check);
    }
    return 0;
}

Of course, it would be cleaner to return the new value, instead of passing the pointer.

Leave a Reply