Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these two syntax in c language?

Tags:

c

loops

First syntax

int i;

for(i=0;i<5;i++)
{
  printf("Hello");
}

Second syntax

for(int i=0;i<5;i++)
{
  printf("Hello");
}

I ask my professor he said both are same but I am not satisfied with this answer.

Please tell whether he was correct or not ?

is both syntax are same or different in some aspect?

like image 806
Sandeep Sahani Avatar asked Nov 18 '25 01:11

Sandeep Sahani


1 Answers

Both code snippets will produce the same output, but there is a difference in meaning.

In the first code snippet, the variable i will continue to exist after the for-loop, whereas in the second code snippet, the scope of the variable i is limited to the body of the for-loop.

Additionally, the second code snippet is not valid for versions of C before C99, as these did not allow the declaration of a variable inside of a for-statement.

It is generally preferred to limit the scope of variable as much as possible, as this results in simpler code.

like image 166
Yun Avatar answered Nov 20 '25 16:11

Yun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!