Archived

This topic is now archived and is closed to further replies.

Odoacer

declarations after printf/scanf?

Recommended Posts

Guest Anonymous Poster   
Guest Anonymous Poster
You have to initialize all your variables at the start of the function in straight C.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
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


}

Share this post


Link to post
Share on other sites
Aldacron    4544
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.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
yep, you''re right, but i don''t know enough english to express myself like you did.
anyway, i think your correction was fair

Share this post


Link to post
Share on other sites
Odoacer    140
Ah all right, thanks guys. It does encourage more structured programming I guess... although doing "for(int i = 0....)" is just convenient sometimes.

Share this post


Link to post
Share on other sites