Bool + array question. need quick help!

Can someone explain step by step what is going on in the code below to get the output "false" ?


1
2
3
4
5
6
7
8
9
10
11
12
   #include <iostream>
    #include <string>
    using namespace std;
    int main()
    {
            bool t[] = {false, true, false & true};
            string u[2] = {"false", "true"}; 
            bool *p; 
            p = t + 2;  // ???????
            cout << u[*p];  // ???????
            return 0;
    }
So answer the second set of "???????", see this http://stackoverflow.com/a/381549/2089675

To support the answer note that the sizeof bool is 1 byte

Now what I really want to know is what this false & true means

EDIT:

the & operator in this code does not refer to reference operator as I thought, it instead refers to the bitwise operator.

So bitwise of false (aka 0) and true (aka 1) (1 & 0) is 0

p = t + 2;
This line uses pointer arithmetic to move the pointer "p" to point to the 3rd element in the array t.

The value of *p at this point is 0 or false

u[*p]

This can be rewritten as u[0] which is "false"
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
 #include <iostream>
    #include <string>
    using namespace std;
    int main()
    {
            bool t[] = {false, true, false & true};
            string u[2] = {"false", "true"}; 
            bool *p; 
            p = t + 2;  // 
            cout << u[*p];  // so this part is really 2nd part of the string u? then why is the output false, rather than true?
            return 0;
    }


What makes it that the output is false on my code? I just don't understand anything.
Last edited on
On line 6, false & true means "false and true", which evaluates to false
for the array t, and the pointer *p, p=t means that p is pointing to t[0]. Pointer arithmetic says that p+1 points to t[1], p+2 points to t[2]. Your t array has t[0]=false, t[1]=true, and as it was pointed before t[2]=false
Topic archived. No new replies allowed.