سؤال

I am almost new to programming.

I see a lot of questions of this type in many question papers and exams

int j= 5;
int i=0;
i= j++ + ++j + j++ - ++j ;

I always predict the wrong value of variable 'i'. My friends suggested many approaches
but all fails in some or the other such expression.

Is there some universal rule/approach to evaluate such type of expressions?

هل كانت مفيدة؟

المحلول

ANSI C explicitly refuses to make any guarantees about the order of argument evaluation for a n-ary operation. Therefore having

y = j++ + ++j

..you might end up with a logical equivalent of one of the following:

x1 = j++; x2 = ++j; y = x1 + x2

..or

x1 = ++j; x2 = j++; y = x1 + x2

depending on compiler, compiler version, OS, and even compilation flags. More complex expressions make things progressively more messy.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top