Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 135 ยท Getting Started

C Syntax

Learn the basic syntax rules of C - main, statements and semicolons, blocks, headers, whitespace and case sensitivity - and how to read compiler errors.

Every language has grammar rules, and C's are short and strict. A C compiler doesn't guess what you meant: a missing semicolon, a misspelled name or an unbalanced brace stops the build. The good news is that the rules are few, and once you know them, you can read the structure of any C program at a glance.

In this lesson you'll take a C program apart into its pieces (directives, functions, statements, blocks and expressions), see what the compiler ignores and what it cares about, and practice reading the messages it prints when something is wrong.

The anatomy of a C program

Here's a small program with every common building block labeled in comments:

C The parts of a program

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

From top to bottom, a C source file is a sequence of:

  • Preprocessor directives such as #include <stdio.h>. They start with #, take up one line each and don't end with a semicolon.
  • Declarations and definitions at file level: functions like square and main, and sometimes global variables or type definitions.

Inside a function body, you find declarations (int side = 4;) and statements (return n * n;, the if, the printf call). The program ran main, which called square, so it printed Big square: 16.

The main function

Execution begins in main. The standard allows two forms on an ordinary computer:

C
int main(void) { /* ... */ }
int main(int argc, char *argv[]) { /* ... */ }

The first takes no arguments. The second receives the program's command-line arguments, which you'll learn in Command-Line Arguments. Both return an int to the operating system: 0 (or EXIT_SUCCESS from <stdlib.h>) for success, anything else for failure.

Warning: You'll find void main() in old books and some embedded code. It isn't standard C for programs that run on an operating system, and it throws away the exit status. Always write int main(void).

Before C23, int main() with empty parentheses meant "a function with unspecified parameters", not "no parameters". C23 finally made () mean the same as (void), but writing (void) is clear in every version of C, so this course uses it.

Statements and semicolons

A statement is one instruction. Most statements end with a semicolon:

C
int total = 0;          /* declaration */
total = total + 5;      /* expression statement (assignment) */
printf("%d\n", total);  /* expression statement (function call) */
return 0;               /* jump statement */

The semicolon is a terminator, not a separator: every simple statement needs its own, including the last one in a block. Compound statements like if, while and for don't take a semicolon after their closing brace.

A semicolon on its own is an empty statement. It's legal and occasionally useful, but in the wrong place it causes a classic bug:

C A stray semicolon

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The ; right after if (temperature > 30) is the entire body of the if: an empty statement. The block in braces that follows isn't part of the if at all, so it always runs, and the program claims it's hot at 12 degrees. GCC notices and prints two warnings: suggest braces around empty body in an 'if' statement (-Wempty-body) and this 'if' clause does not guard... (-Wmisleading-indentation). Remove the stray semicolon and run again.

Blocks and braces

A block (also called a compound statement) is a group of declarations and statements between { and }. Blocks are used as function bodies and as the bodies of if, else, loops and switch.

A block also creates a scope: a variable declared inside it exists only until the closing brace.

C Blocks create scope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Remove the // in front of the commented-out line and run it: GCC reports 'inner' undeclared (first use in this function), because inner stopped existing at the closing brace. Variables and Scope and Storage Classes explain scope in detail.

Tip: Always use braces for the body of if, else and loops, even when it's a single statement. It costs nothing and prevents the bug where you add a second line that looks like it's inside the if but isn't.

Headers

C itself has very little built in: no printing, no strings beyond character arrays, no math functions. Those come from the standard library, and you get access to each part by including its header:

Header Gives you
<stdio.h> printf, scanf, fgets, puts, files
<stdlib.h> malloc, free, exit, strtol, rand, qsort
<string.h> strlen, strcmp, strcpy, memcpy
<math.h> sqrt, pow, sin, floor
<stdbool.h> bool, true, false (built in since C23)
<stdint.h> fixed-width types like int32_t, uint8_t
<ctype.h> isdigit, toupper and other character tests

Angle brackets (#include <stdio.h>) are for system and library headers. Double quotes (#include "shapes.h") are for your own headers; the compiler looks in your project's folders first. Headers usually contain only declarations, which tell the compiler that a function exists and what its parameters are.

What happens if you forget a header? Since C99, the standard forbids calling a function the compiler has never seen, and GCC 14 and newer report it as an error:

C A forgotten header

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

GCC stops with implicit declaration of function 'printf' and helpfully adds include '<stdio.h>' or provide a declaration of 'printf'. Add #include <stdio.h> at the top and it works. (Older compilers only warned about this and then guessed, sometimes producing broken programs.)

Whitespace and layout

Spaces, tabs and line breaks (whitespace) separate words, but the amount doesn't matter to the compiler. These two functions are identical to the compiler:

C
int add(int a, int b) {
    return a + b;
}

int add2(int a,int b){return a+b;}

There are three exceptions to "whitespace doesn't matter":

  • Inside a string literal, every space counts: "a b" has two spaces.
  • Preprocessor directives must be on their own line.
  • You can't split a name or a number: pri ntf is two words, not one.

Since layout is for humans, use it to make structure obvious. This course uses 4-space indentation, one statement per line, spaces around operators and after commas, and the opening brace on the same line as the if, loop or function. The exact style matters less than being consistent; tools like clang-format can format a whole project automatically.

Case sensitivity

C is case-sensitive: total, Total and TOTAL are three different names. Keywords and library names are lowercase, so Printf, INT or Return won't work:

C Case matters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints 10 20 30: three separate variables. Having names that differ only in case is legal, but confusing, so avoid it in real code. By convention, ordinary variables and functions are lowercase with underscores (max_speed), and macros are UPPERCASE (MAX_SPEED). Keywords and Identifiers covers the naming rules.

Expressions

Statements are built from expressions: pieces of code that produce a value. 4, side, side * side, square(side) and even area = 16 are all expressions. Adding a semicolon to an expression turns it into an expression statement. You'll learn how operators combine expressions in the Operators chapter, starting with Arithmetic Operators.

Reading compiler errors

Compiler messages follow the same pattern:

TEXT
main.c:7:5: error: 'count' undeclared (first use in this function)

That's file : line : column : kind : message. The kind is either error (the build fails) or warning (the build succeeds, but something looks wrong). GCC also prints the offending line with a ^ under the exact spot and often a suggestion.

Here's a program with two typical mistakes. It fails on purpose:

C Two errors to fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

GCC reports something like:

TEXT
main.c:5:27: error: 'Count' undeclared (first use in this function); did you mean 'count'?
main.c:6:20: error: expected ')' before ';' token
main.c:7:14: error: expected ';' before '}' token
main.c:4:9: warning: unused variable 'count' [-Wunused-variable]

The first error is the capital C; GCC even suggests the right name. The second is the missing ). The other two messages are only side effects: the missing ) confused the parser about the next line, and count looks unused because its one use was misspelled. Fix the two real mistakes and all four messages disappear; the program prints Count: 3 and Done.

A few habits make errors much less scary:

  • Start with the first message. One mistake can trigger a cascade; fixing the first often clears the rest.
  • Look just before the reported position. A missing ; or ) is usually reported where the compiler noticed the problem, which can be the start of the next line.
  • Read the whole message. "did you mean" and "note:" lines often contain the answer.
  • Change one thing at a time and compile again.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line does NOT end with a semicolon?

    Preprocessor directives like #include are handled before compilation and end at the end of the line, without a semicolon.
  2. 2. What does this print? int a = 1; { int a = 2; } printf("%d", a);

    The inner a is a different variable that exists only inside the block. After the block, a refers to the outer variable, which is still 1.
  3. 3. What is wrong with if (x > 5); { puts("big"); }?

    The ; ends the if statement with an empty body. The block that follows is an ordinary block that runs every time.
  4. 4. A program declares int total = 0; and later uses Total. What happens?

    C is case-sensitive, so Total is a different name that was never declared.
  5. 5. Which signature is the standard way to write a main that takes no arguments?

    int main(void) is valid in every C standard. main must return int on hosted systems, and (void) clearly says it takes no arguments.

Summary

  • A C file contains preprocessor directives, declarations and function definitions; execution starts in int main(void).
  • Simple statements end with a semicolon; a lone ; is an empty statement and can silently break an if or loop.
  • Braces group statements into blocks, and every block is a scope. Always brace if/loop bodies.
  • Headers like <stdio.h> declare library functions; calling an undeclared function is an error in modern C.
  • Whitespace is free-form (except inside strings and directives), and C is case-sensitive.
  • Compiler messages read file:line:column: kind: message; fix the first one first.

Next: Comments, where you'll learn how to leave notes in your code for yourself and others.