user3266083
user3266083

Reputation: 123

Confusion regarding struct values assignment inside and outside a function

struct ConnectFlags {
    bool username;
    bool password;
};    

void functionB(struct ConnectFlags connect) {
     connect.username = true;
     connect.password = true;
}

void functionA() {
    struct ConnectFlags flags;
    functionB(flags);

    if(flags.username && flags.password) {
          printf("Both present\n");
    } else {
          printf("None present\n");
    }
}

int main() {
   functionA();
}

I have the above piece of code and when I execute it, I get "None present". I'm setting the values of username and password to true in functionB so how come I'm still getting them as false.

Any help would be really appreciated.

Thanks!

Upvotes: 0

Views: 28

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

In C, arguments are passed by value, so modifying the arguments in callee won't affect caller's local variables.

Use pointers to moduify caller's local variables.

struct ConnectFlags {
    bool username;
    bool password;
};

void functionB(struct ConnectFlags *connect) {
     connect->username = true;
     connect->password = true;
}

void functionA() {
    struct ConnectFlags flags;
    functionB(&flags);

    if(flags.username && flags.password) {
          printf("Both present\n");
    } else {
          printf("None present\n");
    }
}

int main() {
   functionA();
}

Upvotes: 2

Related Questions