Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have always believed that in C you have to declare a variable at the beginning

ID: 3623740 • Letter: I

Question

I have always believed that in C you have to declare a variable at the beginning of a method, e.g.
int i;
...
for(i=0;...

This is unlike, for example, java where you can declare a variable as needed, e.g.
for(int i = 0;...

A friend of mine however sent me c source code and declared variables as needed (i.e. the java example), and claimed that using devc++ it compiled and ran. Using visual studio 2010, I received tons of errors and it would not compile. Has c updated something and my computer is out of date or is this person "delusional" or something? Please let me know if you can indeed currently declare variables the same way you can in Java, and if so, why is Visual Studio 2010 giving compile time errors.

Explanation / Answer

please rate - thanks

partially

your friend must have compiled the program as C++ and not as C.

Tell your friend in DEV C++ to compile a program as C and not C++, the file must be saved as a type C file, otherwise it compiles as C++. to do this when you do a save as -CPP is the file type default, you must use the drop down menu to choose C. the file will get the extension .C as opposed to .CPP

in C++ you can do

for(int i = 0;...

in C you cannot

however C does follow rules of Scope the same as java

so if I had the following code, variable i would be undeclared when I went to print it after the loop, so it would not compile

int j=0;

for(; ;)

{

int i ;

j++;

i=j;

if(i==3)

       break;

}

printf("%d ",i);

but this is OK - i is only defined within the brackets

int j=0;

for(; ;)

{

int i ;

j++;

i=j;
printf("%d ",i);
if(i==3)

       break;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote