Go Down

Topic: 'for' syntax: for (; *ptr; ptr++) ? (Read 1 time) previous topic - next topic

roypardi

Trying to understand a code snippet (below). I think I understand the pointer stuff but I have never seen that 'for' usage before.

What does the ';' mean/do?

thanks!

Code: [Select]

for (; *ptr; ptr++){
 // do some stuff with *ptr
}

cr0sh

It just means there's a blank initialization; basically, it assumes that ptr has been set previously (prior to the for() loop).
I will not respond to Arduino help PM's from random forum users; if you have such a question, start a new topic thread.

AlphaBeta

that particualr loop is better coded as:
while (*ptr++)

But; explanation:
A for loop consists of three mandatory operands:
The initializer, the condition and the increment.

When the coder simply does ; he explicitly indicates that there are no initialization necessary for this loop. Furthermore the condition is that the value of the cell that ptr currently points to has to be anything but zero, lastly he increments to the next cell in memory.

roypardi

#3
Dec 20, 2010, 06:26 pm Last Edit: Dec 20, 2010, 06:27 pm by roypardi Reason: 1
OK - thanks. Makes sense now.

fwiw - earlier in that code snippet, *ptr is initialized to a null terminated char array - so from your explanation, when it hits \0 (== 0) the loop will end.

Groove

@AlphaBeta: if the operations are 'mandatory', how come you can leave all three out?  
Code: [Select]
#define EVER  (;;)
//
//
 for EVER {

}
Per Arduino ad Astra

Go Up