declarations after printf/scanf?

Started by
4 comments, last by Odoacer 20 years, 6 months ago
I''m trying my hand at vanilla C, and I cant declare any new variables after I use printf/scanf. What gives, and is there a workaround?
Advertisement
You have to initialize all your variables at the start of the function in straight C.
in c, you can´t declare variables anywhere, they must be inmediatly after the begining of the function.
ie:

int main() {
int var;
float another;
char and_so_on;

// from here, you can´t declare any variables


}
quote:
in c, you can´t declare variables anywhere, they must be inmediatly after the begining of the function


Not quite correct. It''s not that they need to be declared at the beginning of a function. They need to be declared at the beginning of a code block.

function my_CFunc(void){   int anInt;   // okay   doStuff();}function my_CPPFunc(void){   doStuff();   int anInt;   // okay in C++, compiler error in C}function anotherCFunc(void){   int anInt;   doStuff();    if(something)   {      float aFloat;   // okay - the braces indicate a code block      doStuff();   }   switch(somethingElse)   {      case A:      {         int anInt;   // okay      }      break;      case B:         float aFloat;   // error         break;   }}


Remember that C predated C++, so many features that C++ has are supposed to be improvements. The ability to declare variables anywhere you like is one of them.
yep, you''re right, but i don''t know enough english to express myself like you did.
anyway, i think your correction was fair
Ah all right, thanks guys. It does encourage more structured programming I guess... although doing "for(int i = 0....)" is just convenient sometimes.

This topic is closed to new replies.

Advertisement