-5
#include <iostream>
using namespace std;

int main() {
// your code goes here
int x=1;
int y;
y=x&&10;
cout<<y;
return 0;
}

The output is 1.

How is the value stored in y? What is the operation of &&? Please explain.

Biffen
  • 6,249
  • 6
  • 28
  • 36
user3516005
  • 31
  • 1
  • 7

3 Answers3

2

This operation

y=x&&10;

is evaluated as:

x && 10
1 (int) && 10 (int)
true && true        // Note any non-zero integer will be evaluated to true
true

Therefore

y = true

But y is an int, so then there is an implicit conversion from bool back to int, which results in y being 1.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
2

If you write "a && b" then both of the variables a and b must equate to true, for the result of the expression to return true, otherwise false will be the result.

For integers, all values which are not zero are considered true. Both of your variables are non-zero so your expression returns true.

When a boolean is stored into an integer, true is expressed as 1 whilst false is expressed as zero.

This is why your application outputs 1.

Chris
  • 2,655
  • 2
  • 18
  • 22
1

y=0 only if you put 0 instead of 10 or assign 0 to x.
if the values of left hand operand and right hand operand both are non-zero y=1 as both represents true.
if one of the operand is 0 then y=0 as 0 represents false.

MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59