Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ AND Operation for -1

While implementing logical operations in the code, I discovered a phenomenon where it should not be entered in the if statement.
It turns out that this is the AND (&&) operation of -1 and natural numbers.

I don’t know why the value 1 is printed in the same code below.
I ran direct calculations such as 1’s complement and 2’s complement, but no 1 came out.

I would appreciate it if you could give me an accurate explanation.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <iostream>

using namespace std;

int main()
{
    int a = 10;
    int b = -1;
    
    int c = a && b;
    
    printf("test = %d",c);

    return 0;
}

>Solution :

The expression a && b is a bool type and is either true or false: it is true if and only if both a and b are non-zero, and false otherwise. As your question mentions complementing schemes (note that from C++20, an int is always 2’s complement), -0 and +0 are both zero for the purpose of &&.

When assigned to the int type c, that bool type is converted implicitly to either 0 (if false) or 1 (if true).

(In C the analysis is similar except that a && b is an int type, and the implicit conversion therefore does not take place.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading