Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the effect of x=x++;? [duplicate]

Tags:

c

#include <stdio.h>

int main()
{
  int x=100;
  x=x++;
  printf("x : %d\n",x); //prints 101
  return 0;
}

What is the reason for output 101? I think output should be 100.

like image 745
Thisara Ranawaka Avatar asked Dec 07 '25 10:12

Thisara Ranawaka


2 Answers

This is Undefined Behaviour, due to Sequence Points.

Between consecutive "sequence points" an object's value can be modified only once by an expression

The end of the previous epxression x=100; is one sequence point, and the end of x=x++; is another.

Basically, your expression has no intermediate 'sequence points', yet you're modifying the value of X twice. the result of this is Undefined Behaviour: Basically, anything could happen: You could get 100, 101 or 42...

like image 140
Roddy Avatar answered Dec 10 '25 00:12

Roddy


Here is what I believe you're looking for:

int main(){
    int x=100;
    printf("x : %d\n",x++); // Will print 100 and then increment x
    return 0;
}
like image 28
Captain Skyhawk Avatar answered Dec 09 '25 23:12

Captain Skyhawk