bool question

What does it mean when it says if(!b)?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Example program
#include <iostream>
#include <string>
void fi(int& a, int& b, int c);

int main()
{
int x=13;
int y=3;
fi(x,y,7);
std::cout<<x<<y;
}
void fi(int& a, int& b, int c){
b=a/b;
if(!b){
a=a%c;
c=a-5;
}
else{
a+=b;
c=a/3;
}
}
Last edited on
if(!b) is equivalent to if(b == false) just like if(b) is equivalent to if(b == true)
So, if b is 0, I would do a=a%c, but if b was any other int value, I would do the a+=b part?
Correct. Personally, I dislike it when integral-types are used in if-statements as if they were booleans (since this is C++ and not C), it's much more explicit and easier to read as if (b == 0).
Last edited on
Yes, though your formatting is very hard to read. Don't be afraid of whitespaces.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Example program
#include <iostream>
#include <string>

void fi(int& a, int& b, int c);

int main()
{
    int x = 13;
    int y = 3;

    fi(x, y, 7);
    std::cout << x << y << std::endl;
}

void fi(int &a, int &b, int c)
{
    b = a / b; //what if b is 0? That would have undefined behavior

    if(!b) //only way this is possible is if a is 0 so !b or !a would work
    {
        a %= c;
        c = a - 5;
    }
    else
    {
        a += b;
        c = a / 3.0f; //if its not a float or double you will have integer division
    }
}


Also having meaningful names instead of these arbitrary ones would make reading it a lot easier. I don't even know what you are trying to do.
Last edited on
Okay, thank you.
After thinking about it...What exactly are you trying to do? The if statement makes no sense..You are pretty much doing this

1
2
3
4
if(a == 0)
{
    c = -5;
}
with some other useless code like
 
a = a % c; == 0 = 0 % c == 0 = 0 == nothing
I'm doing a practice question with given values for a, b, and c and just trying to find out what they return. I don't think the function is meant to do much, it's just showing how to read code properly. i.e. we need to know that !b means the same as b==0, the difference between pass by value and pass by reference, and so on.
Topic archived. No new replies allowed.