In Week 1 of CS50, I saw that David sir was declaring variables in the middle of the block...Isn't this a violation of the standard C syntax ? Aren't we supposed to declare the variable at the start of the block ?

2 Answers 2


You misunderstood that. There is a difference between anything that is syntactically correct and anything that is conventionally correct.

Compilers check for syntax, and not for conventions(generally). A program should be syntactically correct to convey some meaning which the machine can understand. You can't expect machine to understand some random text, Only set of allowed syntax are interpreted correctly. Syntax is designed by humans for machine. Conventions are designed by humans for humans(peers). Sticking to same conventions help your team mates to go through your code easily. It is like there are multiple ways of doing something, it is not guaranteed the way you implement a binary search is exactly similar to the way your friend implements it. By following a same convention, you and your friend's coding habit is made to look same upto a certain level.

A syntactically correct program can be conventionally wrong. Conventions are just coding habits approved by your team. Compiler won't yell for a conventionally wrong program(unless it is designed for).

For example,

while (some_condition) {
    //your code here


while (some_condition) 
    //your code here

both are syntactically correct, but follow different coding conventions. Now it totally depends on you, which one you are comfortable with. Similarly, naming conventions can be either camelCase or snake_case, indentation styles, all of which one to follow and which not, depends on your team/peers/course.

As a beginner, You are supposed to learn both syntax and conventions. As an expert, you will be supposed to learn conventions depending on what your team follows.

  • Yeah I mean't syntax but I was right! In turbo C compiler, we are allowed only to declare a variable at the beginning of the block. But I get it now, that this is ANSI C compiler... we can declare the variable anywhere we want....Am I right? Commented Jun 28, 2015 at 19:17
  • Declaring variables at the starting of the local scope is a good habit, although you can declare them almost anywhere in the program.
    – sinister
    Commented Jun 29, 2015 at 4:22

no. In C, variables have to be declared before they're used. they also have to be in scope. otherwise, you'll get a compilation error.

it's a bad practice to declare all your variables atop of a function or a block in general (unless you really need that). variables should have scope that is as local as possible. see https://youtu.be/FPL_0lpzBjo and https://youtu.be/UC5QAokAupo!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .