I got a code with a for:
for (; indField > 0 && indMask > 0; )
What does this ";"
mean at the beginning and end of the command?
I got a code with a for:
for (; indField > 0 && indMask > 0; )
What does this ";"
mean at the beginning and end of the command?
The for
has 3 "parts":
for ( executar antes de começar ; condição para executar ; executar ao fim da iteração )
You just have to fill in what you need. But you have to ;
anyway.
In this case, the code author did not have to do anything to initialize the loop, it only interested him in the condition to iterate, which is the middle item.
In the same way, if he wanted an loop infinite, it would be enough to omit the condition as well:
for( ;; ) {
// ficarei em loop até o fim dos tempos (ou alguma coisa externa me parar)
}
In this case it means that the person who did does not know what each thing is good for, or like to make funny things :) She should have used while
in this case, after all, there is only one condition and nothing else. The most sensible would be:
while (indField > 0 && indMask > 0)
In this case the structure should not be a for
because it does not use what it has to advantage. The AP confusion that gave rise to the question was precisely because the programmer did not follow the basic precept of doing what is more semantically correct, which is what he and everyone should do. At a minimum it's smarter to use while
there.
Technically, it means that you did not want to initialize a variable, as it is common to for
. also did not want to perform anything at each step of the iteration of the loop, noticed that there is nothing also after the last ;
?.
A for
is:
for ( //o comando
int i = 0; //a inicialização da variável (geralmente, pode ser qualquer ação)
i < 10; //a condição de término do laço (sempre tem que ser um resultado booleano
i++ //o passo a executar em cada interação, o incremento é muito comum
) { //fecha o comando
Note that for
is always composed of 3 different actions , and then it usually has a block of must be run on the loop. In thesis all 3 parts can be omitted, depending on what you want.
Other things few people know is that there may be more than one expression in each of these parts, if separated by commas, and this is not exclusive to for
, it is valid in any context where statment is expected . Example:
for (int i = 0, j = 0; i < 10; i++, j++) { ... }
Until the condition can do this, but only the last boolean expression will be considered as the end result to determine whether the loop should continue or not.
Then each of the 3 statements of for
can have zero to "infinite" expressions.
See What's the difference between the while, for, while and foreach? . It's another language, but it's worth the same.