Examveda

What will be the final values of i and j in the following C code?
#include <stdio.h>
int x = 0;
int f()
{
    if (x == 0)
        return x + 1;
    else
        return x - 1;
}
int g()
{
    return x++;
}
int main()
{
    int i = (f() + g()) || g();
    int j = g() || (f() + g());
}

A. i value is 1 and j value is 1

B. i value is 0 and j value is 0

C. i value is 1 and j value is undefined

D. i and j value are undefined

Answer: Option A

Solution (By Examveda Team)

Understanding the C code:
The code involves three functions:
`f()`: This function checks the value of a global variable `x`. If `x` is 0, it returns 1; otherwise, it returns `x - 1`.
`g()`: This function returns the current value of `x` and then increments `x` (post-increment).
`main()`: This is where the magic happens. It calculates `i` and `j` using the `f()` and `g()` functions and the logical OR operator (`||`).

Let's trace the execution step-by-step:
Initially, `x` is 0.
For `i`:
1. `f()` is called first. Since `x` is 0, `f()` returns 1.
2. `g()` is called next. `g()` returns 0 (the current value of `x`) and then increments `x` to 1.
3. The expression becomes `1 + 0 || 0`. Since `1 + 0` evaluates to 1 (which is true in boolean context), the `||` operation short-circuits and the result is 1. Therefore, `i` becomes 1.

For `j`:
1. `g()` is called first. `g()` returns 1 (the current value of `x`, which is now 1) and increments `x` to 2.
2. The `||` operation checks the left side (which is now 1, meaning true). Because of short-circuiting of `||`, the right side (`f() + g()`) is not evaluated. The result is 1. Therefore `j` becomes 1.

Conclusion:
The final values are: `i = 1` and `j = 1`. Therefore, the correct option is A.

This Question Belongs to C Program >> C Fundamentals

Join The Discussion

Comments (1)

  1. Gamma Killer
    Gamma Killer:
    1 year ago

    Answer is wrong instead it should be option A i.e. i = 1, j = 1, here's the reason:
    evaluating i
    f() + g() => 1 + 0
    (f() + g()) + g() => 1 || g() => 1
    therefore i = 1 because g() is not evaluated because of short circuit evaluation concept in c
    evaluating j
    since x = 1,
    g() => 1
    g() || (f() + g()) => 1 || (f() + g())
    terminates second evaluation because of short circuit.
    and hence results in j = 1;
    so the answer is option A

Related Questions on C Fundamentals