bool question

Aug 30, 2014 at 9:41pm
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 Aug 30, 2014 at 9:43pm
Aug 30, 2014 at 9:43pm
if(!b) is equivalent to if(b == false) just like if(b) is equivalent to if(b == true)
Aug 30, 2014 at 9:46pm
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?
Aug 30, 2014 at 9:49pm
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 Aug 30, 2014 at 9:51pm
Aug 30, 2014 at 9:51pm
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 Aug 30, 2014 at 9:52pm
Aug 30, 2014 at 10:01pm
Okay, thank you.
Aug 30, 2014 at 10:05pm
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
Aug 30, 2014 at 10:09pm
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.