this is more of a C related programming question . . .
What would the following statement do? Does it loop through the first argument and corresponding arguments in a command application?
hey, thank you for replying now I understand that any statement in a while loop always results to TRUE as long as specified without a NOT operator, correct?
if i publish the full program, could I ask a couple of more questions?
A "not" operator inverts the result of the condition, but this is not the only way to write a condition that, eventually, evaluates to false 😏
Furthermore, using a comma inside of a while condition is pretty unusual. In this case, only the result of the last comma-separated statement determines whether the while loop continues. The other statements are still executed, but their results are discarded!
int main(int argc, char** argv) {
while (argc--)
printf("%d -> %s\n", argc, *argv++);
}
Usually you'd use a for loop as per kigar64551 above and not change the values of argc and argv used in main(). Note that doing it this way the values shown by argc don't match the argument index values in argv. The program name is argv[0] (the first argument) but here it's shown as the highest value of argc. This could be confusing.
Using a , operator in the while condition is problematical in this situation. The various expressions separated by , are evaluated left to right with the value of the final evaluated expression (the rightmost one) being the result of the statement. So with argc--, argv++ the while condition continues while the value of argv++ is not zero. argc is decremented but it's value isn't used for the condition evaluation. As argv is a memory pointer this is effectively an infinite loop and as soon as argv takes on an invalid value for pointer dereferencing there is a run-time error.
As argv is a memory pointer this is effectively an infinite loop and as soon as argv takes on an invalid value for pointer dereferencing there is a run-time error.
I think it happens to work correctly here, because argv is actually a pointer to a pointer (i.e. pointer to an array of pointers to null-terminated strings), and because the pointer to the last command-line argument string is followed by an additional NULL pointer.
C11 5.1.2.2.1 Program startup
The value of argc shall be nonnegative. argv[argc] shall be a null pointer.