im having troubles on how to understand the bool data type can someone please help me understand it and can you give some sample programs for me to study :D thanks
I'm not good at explain something but I'll try
Bool is a data type that holds true or false for its value, ex:
1 2 3 4 5
bool loop=true; int x=0;
while(loop){
if(x==5) loop=false;
x+=1;
}
If you're using bool as return value of function, you can call that function inside if or loop as its condition ex;
1 2 3 4 5 6 7 8 9
bool check(int x){
if(x>5)returnfalse;
elsereturntrue;
}
int main(){
int x;
std::cin>>x;
if(check)std::cout>>"lol";
}
Maybe it looks like that it doesn't need a function to do that but its useful for more complex code that return true or false because you can't put the whole code inside if condition
Yes, in other words if x is > 5 then it will output "lol" otherwise it will do nothing. Though, they doesn't actually call the function. They compare the address to a non-zero number which should always be true.
Though, I would just do something like
1 2 3 4 5 6 7 8 9 10 11 12 13 14
bool greaterThan(int x, int y)
{
return x > y;
}
int main()
{
int x = 0;
std::cout << "Please enter a number: ";
std::cin >> x;
std::cout << x << " is ";
if(greaterThan(x, 5)) std::cout << "greater than 5." << std::endl;
else std::cout << "less than or equal to 5." << std::endl;
return 0;
}
Please enter a number: 10
10 is greater than 5.
Though instead of the if/else I would personally use the ternay operator. std::cout << x << " is " << (greaterThan(x, 5) ? "greater than 5." : "less than or equal to 5.") << std::endl;