Doubt about iteration with multiple parameters

Asked

Viewed 64 times

1

This loop performs Log_base_2 of an integer value, at the end the result is available in the variable i.

Why make a shift in the form valor >> 1 has no effect compared to valor = valor >> 1 which by the way was the way I managed to avoid a loop infinite?

for(i = 0 ; valor != 1 ; valor >> 1, ++ i); //loop infinito
for(i = 0 ; valor != 1 ; valor = valor >> 1, ++ i); //execução normal
  • Just a detail, it seems to me that only calculates the whole part of the log2 of the number.

  • Yes, this was intentional. I used to manipulate the bits of a word in a cache memory simulator.

1 answer

1


The first is just calculating a number and throwing away, doesn’t guard anywhere, so it has no effect anywhere.

The ++i has effect because it is a compound operator. In fact it is the same thing as doing i = i + 1.

In that particular case you can do so valor >>= 1, which is the same as valor = valor >> 1. This is also a compound operator as well as a i += 1 also.

  • Yes, I get it! Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.