I'm confused on how this program works
Well, "works" is a very poor observation / decision here. This is undefined behavior.
You're attempting to use the value of an automatic local variable n
while it is indeterminate. This invokes the UB.
To quote the C11
standard, chapter ยง6.7.9
If an object that has automatic storage duration is not initialized explicitly, its value is
indeterminate. [...]
So, in your case, n
meets the criteria described above, and hence the content is indeterminate.
Now, after that, in case you try to use a variable while it holds indeterminate value and either
- does not have the address taken
- can have trap representation
the usage will lead to undefined behavior. That is exactly the case here.
That said, for a hosted environment, the conforming signature of main()
is int main(void)
, at least.
Best Answer
The
for
statement works like:for (initialization; test-condition; update)
And any or all of those three can be omitted (left blank). So:
for (;;)
is an infinite loop1 equivalent towhile (true)
because there is no test condition. In fact,for (int i=0; ;i++)
would also be an infinite loop1.for ( ; *s != '\0'; s++)
is a loop with no initialization.s
will point to the beginning of (probably) a string and is incremented until it reaches the null character'\0'
denoting end-of-string. This essentially means loop through all characters of the strings
1 The loop will still be interrupted if there's a
break
statement in the loop body, or a call toexit()
, etc...