I am beginning to learn C++ struct. After creating a struct named Person, I tried to declare a boolean variable named genderBoolean in the struct of Person, and a string variable named gender. I tried to use if-else statement for the following condition: if genderBoolean is true, then gender is male, but if genderBoolean is false, then gender is female. I tried to put the if-else statement outside of the struct, but the IDE says
Identifier "genderBoolean" is undefined
which causes another compilation error.
It seems that if-else statement cannot be used within struct in C++. I found out that adding a # before the if statement and adding #endif can solve the compilation error of "expected a declaration" in Microsoft Visual Code 2022, but the output of the program is:
"Name = Mike Gender = Age = 50 Nationality = American"
I expected its output to be : "Name = Mike Gender = male Age = 50 Nationality = American"
My code also generates compilation message that says the variable genderBoolean is uninitialized, but it can run:
#include <iostream>
using namespace std;
int main() {
struct Person {
string name;
bool genderBoolean;
string gender;
string age;
string nationality;
#if(genderBoolean == true) {
gender = "male";
}
else if (genderBoolean == false) {
gender = "female";
}
#endif
};
Person person1;
person1.name = "Mike";
person1.genderBoolean = true;
person1.age = "50";
person1.nationality = "American";
cout << "Name = " << person1.name << " Gender = " << person1.gender <<
" Age = " << person1.age << " Nationality = " << person1.nationality <<
endl;
return 0;
}
I tried to put the if-else statement outside of the struct but it says identifier "genderBoolean" is undefined.
I expected its output to be : "Name = Mike Gender = male Age = 50 Nationality = American"
What actually resulted : "Name = Mike Gender = Age = 50 Nationality = American"