Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading