0

I'm having a difficult time with operator precedence. Could somebody explain specifically part (A) why c=1. part (B) why the increment and decrement don't cancel each other out, part (C), what happens with c?

#include<iostream>
using namespace std;
int main(){
//A
long x = 3, y = 1;
long a, b, c;
a = b = x;
(c = b) = y;
cout << a << ", " << b << ", " << c <<endl; //3, 3, 1

//B
long x = 3, y = 10, z = 4;
long a = (--x)++;
long b = (z += y);
cout << a << ", " << b <<endl; // 2, 14

//C
long x = 3, y = 5;
long a, b, c;
a = x > y;
c = ((b = 13) || (b = 20));
cout << a << ", " << b << ", " << c <<endl ;
}
Bellerofont
  • 1,081
  • 18
  • 17
  • 16
Hannah
  • 1
  • 1

3 Answers3

0

// Part A c=1 because (c=b)=y . First value of B is assigned to c then value of y is assigned to c . Thats why C has value of y. so c==1;

// Part B long a = (--x)++; Here increment and decrement doesnt cancel each other because it is post increment so first value is assigned to a variable and then it is incremented . so --x means 2 . So value of 2 is assigned to a and then x get his old value of 3.

// Part C

value of a is 0 because x>y statement is false so it gets 0 value. value of b is 13 because precedence is from right to left so b is assigned value 13 and c is assigned true because statement is true inside bracket

praneet drolia
  • 671
  • 1
  • 6
  • 15
0

A) c is assigned value of b and then value of y
B) x is decremented first, then assigned to a and then incremented. See difference between a = ++x and a = x++ I.e. betwen prefix operator and postfix operator.
C) I will answer it wit question. What values can logical operator || retrun? And what happens when logical operator takes integers as input?

Marek Vitek
  • 1,573
  • 9
  • 20
0

Alright let me check my skills in mess cleanup:

using namespace std;
//A
{
    long x{3};
    long y{1};
    long a;
    long b;
    long c;
    long & b_ref{b = x}; // b is 3
    a = b_ref;           // a is 3
    long & c_ref{c = b}; // c is 3
    c_ref = y;           // c is 1
    cout << a << ", " << b << ", " << c <<endl; //3, 3, 1
}
//B
{
    long x{3};
    long y{10};
    long z{4};
    long & x_ref{--x};    // x is 2
    long tmp_x{x_ref};    // 2
    x_ref = x_ref + 1;    // x is 3
    long a{tmp_x};        // a is 2
    long & z_ref{z += y}; // z is 14
    long b{z_ref};        // b is 14
    cout << a << ", " << b <<endl; // 2, 14
}
//C
{
    long x{3};
    long y{5};
    long a;
    long b;
    long c;
    bool x_gt_y{x > y};            // false
    a = x_gt_y;                    // a is 0
    long & b_ref1{b = 13};         // b is 13
    long & b_ref2{b = 20};         // b is 20
    bool b_or_b{b_ref1 || b_ref2}; // true
    c = b_or_b;                    // c is 1
    cout << a << ", " << b << ", " << c <<endl ;
}
user7860670
  • 35,849
  • 4
  • 58
  • 84