2

I have been notified by many that in C, definitions must be right after main() block starts instead of defining right before using. You could also count functions in since function definitions are related to same topic. After doing some search on stackoverflow and web, i could not find the answer to my question or i just could not find the keyword to search.

int main(){ //defining at the beginning of main
int x=0;
.
.
.
function(x);
return 0;
}

OR

int main(){ //defining right before using
.
.
.
int x=0;
function(x);
return 0;
}
Sabri Özgür
  • 632
  • 5
  • 10
  • `function(x);` is not a function definition here, it's a function call. For your question, the former is preferred to comply with older standards. You may have new variables between curly braces: `int main(){ int x=5; do_sth(); if(x) { int y; } }`. edit: ah, sorry. but complying with older standards part of this comment is still valid. – holgac Apr 24 '15 at 10:49
  • I actually meant that same process is valid while defining a function. That `function(x);` is there just to show that i used the variable. – Sabri Özgür Apr 24 '15 at 10:51

2 Answers2

1

It is perfectly fine to declare/define variables anywhere inside the body of a statement/function.

In an old, withdrawn version of the C standard called "C90", you were forced to always declare/define variables at the beginning of a block. However, this restriction was removed ages ago.

It may still be convenient to declare/define all variables at the same place at the top of the block though, so that you can easily find them when reading the code.

There is no performance difference between declaring the variable at top of the block or just before it is being used. The compiler will generate the same machine code in either case.

Lundin
  • 195,001
  • 40
  • 254
  • 396
0

You can declare a variable anywhere in a program but it should always be declared before using the variable.

A better option is declaring all variables together in the beginning of a function as it improves readability of the code.

user-ag
  • 224
  • 3
  • 20