0

The Output of this program is coming out to be 4.00000. I don't know that what will happen first multiplication of 2 with c and then increment takes place or multiplication of 2 with increased c?

int main()        
{
int c=1;
c=c+2*c++;
printf("\n%f", c);
return 0;
}
Jay Patel
  • 505
  • 6
  • 10
  • 1
    The thing that will happen first (and in this kind of case always) is undefined behaviour. – Haris Aug 24 '16 at 15:57
  • read this: http://stackoverflow.com/questions/7506704/difference-between-sequence-points-and-operator-precedence-0-o ... the key bit: "It does not matter that due to operator precedence the order in which the two operators are evaluated is well-defined, because the order in which their side effects are processed is still undefined." – Woodstock Aug 24 '16 at 15:58
  • 1
    Also `%f` is for floating point numbers, you're printing an int so use `%d` – flau Aug 24 '16 at 15:59

1 Answers1

0

This invokes undefined behavior, which means that anything can happen in your program.

See the C99 spec, specifically J.2 Undefined Behavior:

The behavior is undefined in the following circumstances: [...]

  • Between two sequence points, an object is modified more than once, or is modified and the prior value is read other than to determine the value to be stored (6.5).

As a rule of thumb, "between two sequence points" means between two semicolons (;) that end a statement. The "object" mentioned in the excerpt is the variable c.

With that out of the way, we can clearly see that the object is modified twice between two sequence points. It's modified once during the evaluation of the expression c++ and once during the assignment.

Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104