开发者

java vs c integer [duplicate]

开发者 https://www.devze.com 2023-03-02 18:00 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: ++i + ++i + ++i in Java vs C
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

++i + ++i + ++i in Java vs C

Using Java:

public class Main {
    public static void main(String[] args) {
        int a=10;
        a=a++;
        a=a++;
        System.out.println(a);
    }
}

Output: 10

开发者_运维百科Using turbo C:

void main(){
    int a=10;
    a=a++;
    a=a++;
    printf("%d",a);
}

Output: 12 How is this happening?


a=a++ is undefined behavior. so even two C programs might return different results for that.

the postfix ++ increments the variable after the operation, but you don't know if it will increment the variable after the calculation of the right expression or after the assignment, and you don't know if it will affect the result or not.

Assuming b is a temporary register / variable used for the calculation of the right expression:

option 1:

a is assigned to b, b assigned to a, b incremented by one. (a will be the same)

option 2:

a is assigned to b, b incremented by one, b assigned to a. (a will be incremented)

0

精彩评论

暂无评论...
验证码 换一张
取 消