English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Can I use "for(int i=0; i< 5; i++)"?

2006-10-06 12:41:05 · 3 answers · asked by Aakash 1 in Computers & Internet Programming & Design

3 answers

in JAVA that's ok.
in C++ that's ok.
in any scripting language that's ok.

in ANSI C, you cannot do that. you have to declare your variables in the very beginning of you program or function definition.

An example:
I just tested what you asked, the compiler of MS VC++ gives this error for my "test.c" program.
code:

#include

main()
{
int hede=0;
for ( int c=0;c<5;c++)
{
printf("%d", hede);
}
}

even for this very little code i got 7 errors & 1 warning:
first error is:
C:\Documents and Settings\Owner\Desktop\dene.c(6) : error C2143: syntax error : missing ';' before 'type'


i hope this helps , peace

2006-10-06 13:14:24 · answer #1 · answered by Syntax-Error 3 · 2 0

hi,
you can assign a value to a variable in the for loop.but the difference between
for(i=0;i<5;i++;) and for(int i=0;i<5;i++) is that in the later case the variable will be local variable to that loop and in the former case the variable is global variable.
(i.e) take a sample program;
main()
{
int i = 10;//global variable
...................................
..................................
for(int i=0;i<5;i++)//local variable
{
i++;//local variable
printf("the local variable value is %d",i);
}
printf("the global variable value is %d",i);
}
in this example I took a variable i and initialized it wit 10.if u take the for loop the same variable is initialized with 0 and as local variable value will overwrite the value of global variable
so the i value will be 0 and it will execute the for loop for 5 times and prints the i value and comes out of the loop.here the local value of the variable will be replaced with the value of global variable.so in the printf the variable value will be 10
if u don't understand it send me mail i will explain it or execute the program and check the output you can understand.

2006-10-06 20:02:20 · answer #2 · answered by chaitanya 2 · 0 0

No, that is Java syntax, and I believe C++ works too, but not in C.

2006-10-06 19:46:57 · answer #3 · answered by Andy T 7 · 0 0

fedest.com, questions and answers