简体   繁体   中英

int and long cast in loop for array

I'm trying to understand. What will happen as n passes from int range to long int range and why doesn't this pose a conflict for the compiler? I'm intending to use this to create an array of size n (I know it will take massive amounts of memory and it's not meant to to the final value) which I believe can only by indexed by int and not long although so far no errors from eclipse. Help understanding would be great thanks.

for (int n= 10; n <= ((long)(500*Math.pow(10,6))); n=n*2)

The for loop as such does not see n as anything other than an int, it manipulates n in

n = n * 2

but here it's an int, so you'll get overflow behaviour n will never exceed the maximum int value.

In evaluating the termination condition the for loop needs a boolean

 n <= ((long)(500*Math.pow(10,6)))

that is an int compared with a long, so n is converted to a long only for the purpose of evaluating the comparison think of this as

 long tmp = n;
 if ( tmp <= bigLongValue)

n itself is not affected.

Even an int is not required

Try this for(float t=0; t<=2;t=t+1){ System.out.println(t); }

So for loop is irrespective of the values and types

and to create an infinite loop

for(;;){ }

can be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM