What is the difference between prefix and postfix operators?

前端 未结 13 1856
天命终不由人
天命终不由人 2020-11-22 08:01

The following code prints a value of 9. Why? Here return(i++) will return a value of 11 and due to --i the value should be 10 itself, can anyone ex

13条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 08:45

    There are two examples illustrates difference

    int a , b , c = 0 ; 
    a = ++c ; 
    b = c++ ;
    printf (" %d %d %d " , a , b , c++);
    
    • Here c has value 0 c increment by 1 then assign value 1 to a so value of a = 1 and value of c = 1
    • next statement assiagn value of c = 1 to b then increment c by 1 so value of b = 1 and value of c = 2

    • in printf statement we have c++ this mean that orginal value of c which is 2 will printed then increment c by 1 so printf statement will print 1 1 2 and value of c now is 3

    you can use http://pythontutor.com/c.html

    int a , b , c = 0 ; 
    a = ++c ; 
    b = c++ ;
    printf (" %d %d %d " , a , b , ++c);
    
    • Here in printf statement ++c will increment value of c by 1 first then assign new value 3 to c so printf statement will print 1 1 3

提交回复
热议问题