C Programming – Variable Not Declared in For Loop Condition Still Works

c++for-loopinitializationvariables

I wrote the below code to find the sum of all digits in C, and when I compiled and ran it, it was successful.
But, only later I realized that i had not entered any value for the variable 'n' in the for loop's condition.
I'm confused on how this program works, even when there is no value assigned to the condition variable.
I would like to be clarified of the same.

#include<stdio.h>
void main()
{
int no,a,b,n,sum=0;
printf("Enter the number to be added");
scanf("%d",&no);
for(int i=0;i<n;i++)
    {
     a=no%10;
     b=no/10;
    sum=a+sum;
    no=b;
    }   
printf("The sum is %d",sum);
}

Best Answer

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.