boolean

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)return false;
   else return true;
}
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
in your second example it means that if x>5 it returns false
and if not it return true

and in the body of the program once the user inputed x the function will test whether the inputed number is true or false ? am i right?
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;
Thanks ill continue to practice using bool data type
Topic archived. No new replies allowed.