Java learning magical i = i ++

xiaoxiao2021-03-06  72

Those who have learned a computer language must know the results of J = i , the value of the entire expression is i, and the value of i is I 1; then what is I = i What is the situation? The following is a test with java and c, respectively:

Java:

Public Class Test

{

Public static void main (string args [])

{

Inti, J;

i = 0;

For (j = 0; j <5; j )

{

i = i ;

System.out.println ("i =" i);

}

}

}

C:

#include

Main ()

{

Inti, J;

i = 0;

For (j = 0; j <5; j )

{

i = i ;

Printf ("i =% D / N", I);

}

}

You may ask, what is the problem with such a simple program? Yes, if you don't believe, you can run these two programs, and the results get the results are very shocked.

The result of the first Java program is as follows:

i = 0

i = 0

i = 0

i = 0

i = 0

The result of the second C program is as follows:

i = 1

i = 2

i = 3

i = 4

i = 5

Also i = i , why do the results have such a big difference? It turned out to have a problem over the compiler. Java's compiler will allocate a memory space for the variable operation when encounter i and i- -, to store the original value, and after completing the assignment, Block memory release, let's take a look at the situation of j = i :

i's original value stored in the rear, the last value will assign a value to J, so after j = i , J will get the value of i, and I will be self-added, so, after release memory, it is originally stored The places of J and I will result in: j (the value at this time is equal to the initial I value) and I (I self-add value).

Understand the above questions, let's take a look at i = i :

So the result of this last cycle is still i (ie 0).

I = i in the C language is just the content of i , so the conclusion will be different. This situation shows that the mechanism of the processing syntax of Java and C is different. If you only enter i in the program, there will be no such problem, so everyone should be extra careful when using i = i in the future program. There will be no problem with i .

转载请注明原文地址:https://www.9cbs.com/read-120781.html

New Post(0)