Interview Questions

Microsoft Interview Question for Software Engineers about C ......

Microsoft Interview Questions and Answers


(Continued from previous question...)

22. Microsoft Interview Question for Software Engineers about C ......

Question:
main() {
int i,j;
j = 10;
i = j++ - j++;
printf("%d %d", i,j);
}
The output of this is 0, 12
can anyone please explain me the logic


maybe an answer1:

The result is undefined. Side effects in an expression do not have a set order of evaluation in C. The outcome is up to the compiler's implementation.

A compiler may decide to evaluate the side effects of an expression at a different time. The side effect of j++ is permanently incrementing the value of j after using the current value.

This is not a simple expression. This is an arithmetic expression containing two side effects. One of the side effects can potentially impact the rest of the processing.

Since the subtraction has a set operator order of precedence (left-to-right), the code will first compute (j++). The value of which is the current value of j, 10. This is the left-hand side of the subtraction, the minuend. The side effect making j permanently represent a value one higher (j+=1) may not occur until later (the end of the line's execution), even though this evaluates. Next, the right-hand side of the subtraction, the subtrahend, will evaluate. Now comes the reason we have an undefined outcome. Did the side effect of evaluating the minuend take effect immediately, or will it not take effect until the line is completed? The compiler decides this question, then evaluates (j++) again, yielding a value of 10 or 11.

With ++j - ++j, you may find the same issue. Do we get 11-12 (side effect happens immediately) or 11-11 (side effect happens at the end of the line's execution)?

Do not depend on side effects happening at a particular time in code.


maybe an answer2:

Just experiment with code :
template <typename T>
class op_test
{
private:
T val_;
op_test();
public:
explicit op_test(const T& v)
: val_(v)
{
}
virtual ~op_test(){}

op_test& operator-(const op_test& rhs){
std::cout << "called operator-" << std::endl;
val_ = val_ - rhs.val_;
return *this;
}

op_test& operator++(int i)
{
std::cout << "called operator++" << std::endl;
val_ += 1;
return *this;
}
};

int main()
{
op_test<int> a(12), res(0);
res = a++ - a++;
}

It produce following result for G++

called operator++
called operator++
called operator-

(Continued on next question...)

Other Interview Questions