C Programming - Expressions

Exercise : Expressions - General Questions
1.
Which of the following is the correct order of evaluation for the below expression?
z = x + y * z / 4 % 2 - 1
* / % + - =
= * / % + -
/ * % - + =
* % / - + =
Answer: Option
Explanation:
C uses left associativity for evaluating expressions to break a tie between two operators having same precedence.

2.
Which of the following correctly shows the hierarchy of arithmetic operations in C?
/ + * -
* - / +
+ - / *
/ * + -
Answer: Option
Explanation:

Simply called as BODMAS (Bracket of Division, Multiplication, Addition and Subtraction).

How Do I Remember ? BODMAS !

  • B - Brackets first
  • O - Orders (ie Powers and Square Roots, etc.)
  • DM - Division and Multiplication (left-to-right)
  • AS - Addition and Subtraction (left-to-right)

  • 3.
    Which of the following is the correct usage of conditional operators used in C?
    a>b ? c=30 : c=40;
    a>b ? c=30;
    max = a>b ? a>c?a:c:b>c?b:c
    return (a>b)?(a:b)
    Answer: Option
    Explanation:

    Option A: assignment statements are always return in paranthesis in the case of conditional operator. It should be a>b? (c=30):(c=40);

    Option B: it is syntatically wrong.

    Option D: syntatically wrong, it should be return(a>b ? a:b);

    Option C: it uses nested conditional operator, this is logic for finding greatest number out of three numbers.


    4.
    Which of the following is the correct order if calling functions in the below code?
    a = f1(23, 14) * f2(12/4) + f3();
    f1, f2, f3
    f3, f2, f1
    Order may vary from compiler to compiler
    None of above
    Answer: Option
    Explanation:
    Here, Multiplication will happen before the addition, but in which order the functions would be called is undefined. In an arithmetic expression the parenthesis tell the compiler which operands go with which operators but do not force the compiler to evaluate everything within the parenthesis first.

    5.
    Which of the following are unary operators in C?
    1. !
    2. sizeof
    3. ~
    4. &&
    1, 2
    1, 3
    2, 4
    1, 2, 3
    Answer: Option
    Explanation:

    An operation with only one operand is called unary operation.
    Unary operators:
    ! Logical NOT operator.
    ~ bitwise NOT operator.
    sizeof Size-of operator.

    && Logical AND is a logical operator.

    Therefore, 1, 2, 3 are unary operators.