Search code examples
c++functionlinkerheaderboolean

C++ function does not update variable



I am currently coding a function, that has to update the value of a boolean.
For some reason though, it does not do this. Let me show you a simplified version:

main.cpp

#include <iostream>
#include "header.h" 


int main(){

bool limit = true;

test(limit);

if (limit == false){cout << "hi";}

}

header.h

void test(bool x);

header.cpp

#include <iostream>
#include "header.h"

void test(bool x){

x = false;
}

I define the bool "limit" in my main function. Then I pass it to the function "test" that is located in header.cpp. In this function, the bool limit is set to false. However, returning to main.cpp the bool is still true. This I see, because the if condition is not called. I suspect that the error has to do with the information being passed between the files. Do you know the real reason and a possible alternative?


Solution

  • When you declare the function test as

    void test(bool x);
    

    the parameter bool x is passed by value. That is, the computer makes a copy of the variable that you pass to test. So when test updates such a variable, you are just modifying a temporary variable, with no effect on the bool limit that you pass to it from main.

    If you intend to update x you should pass a reference and declare test as

    void test(bool& x);