C: Syntax: Structure and Semicolons

🗓 Last updated: 2026-11-30👤 Written by: Harper✓ Reviewed by: Dana🏷 Category: C Tutorial

Learning C's basic syntax is like learning the strokes of Chinese characters — horizontal, vertical, left-fall, right-fall seem simple, but every beautiful piece of writing is built from them.

TL;DR: Every C program has the same skeleton: preprocessor directive, main function, braces, and return 0;. Statements end with semicolons, blocks use {}, output uses printf, and comments use // or /* */. These five rules cover most beginner code.

Reference entries in this section: printf #include scanf int char short long float double void signed unsigned

1. Program Structure

Every C program shares a fixed skeleton. No matter how complex the program gets, the core structure stays the same:

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // Return result
    return 0;
}

This is the smallest valid C program — it does nothing, but the structure is complete. Let's break it down:

(1) Preprocessor Directives

#include <stdio.h> is a preprocessor directive. It starts with # and is processed before compilation.

You'll encounter other common header files as well:

Header What It Provides
<stdio.h> Input/output (printf, scanf)
<stdlib.h> General utilities (malloc, exit)
<math.h> Math functions (sqrt, sin)
<string.h> String operations (strlen, strcpy)
<ctype.h> Character classification (isdigit, toupper)

(2) The main Function

C
// Function definition
int main(void) {
    // Return result
    return 0;
}
🔥 Common Mistake: main is the single entry point of a C program. You can only have one main function — the operating system calls it to start your program.

(3) Other Forms of main

You may see a different form of main in some textbooks:

TEXT
int main(int argc, char *argv[])

This form can receive command-line arguments, which we'll cover in detail later. For now, int main(void) is all you need.

⚠️ Note: Some older textbooks use void main(). This is not standard C and some compilers will warn about it. Always use int main(void).


2. Statements and Semicolons

In C, the semicolon ; marks the end of a statement. Think of it like a period at the end of a sentence — just as a sentence needs a period, a statement needs a semicolon.

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // Variable declaration
    int age = 18;
    age = age + 1;
    // I/O operation
    printf("I am %d years old\n", age);
    // Return result
    return 0;
}

Each line is a statement, ending with a semicolon.

A common mistake — forgetting the semicolon:

TEXT
int age = 18

The compiler doesn't recognize "line breaks" — it only recognizes semicolons. Theoretically, you could write all your code on one line:

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) { int age = 18; age = age + 1; printf("%d\n", age); return 0; }

While syntactically legal, this is never recommended. Good coding style puts one statement per line.

💡 Tip: A lone semicolon is also a valid statement, called a null statement — it does nothing:

C
;

It's useful in certain special cases (like an empty loop body), but you don't need to worry about that now.


3. Code Blocks

A group of statements enclosed in curly braces {} forms a code block (also called a compound statement):

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // Variable declaration
    int x = 10;
    // Variable declaration
    int y = 20;
    // Variable declaration
    int sum = x + y;
    // I/O operation
    printf("Sum = %d\n", sum);
    // Return result
    return 0;
}

The entire main function body is one code block. Code blocks define scope — variables declared inside a block cannot be accessed outside it.

Code blocks can be nested:

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // Variable declaration
    int a = 1;
    {
        // Variable declaration
        int b = 2;
        // I/O operation
        printf("a + b = %d\n", a + b);
    }
    // Return result
    return 0;
}

The inner block can access the outer a, but the outer block cannot access the inner b.

⚠️ Note: Even if a code block contains only one statement, it's best to include the curly braces. This prevents bugs when you later add more statements and forget to add braces.


4. The printf Function

printf is the most commonly used output function in C. The name comes from print formatted.

(1) Basic Usage

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // I/O operation
    printf("Hello, World!\n");
    // Return result
    return 0;
}

The content inside the double quotes is called the format string and is printed as-is (except for escape characters).

(2) Format Specifiers

The power of printf lies in formatting variable values for output:

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // Variable declaration
    int age = 18;
    // Variable declaration
    float height = 1.75f;
    // Variable declaration
    char grade = 'A';
    // I/O operation
    printf("Age: %d\n", age);
    // I/O operation
    printf("Height: %.2f\n", height);
    // I/O operation
    printf("Grade: %c\n", grade);
    // Return result
    return 0;
}

Common format specifiers:

Specifier Type Example Output
%d int 42
%f float / double 3.140000
%.2f float (2 decimal places) 3.14
%c char A
%s string hello
%ld long 100000
%x hexadecimal integer 2a
%o octal integer 52
%% literal percent sign %
💡 Tip: You can use multiple specifiers in a single printf — they correspond to the arguments in order:

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // Variable declaration
    int a = 3, b = 4;
    // I/O operation
    printf("%d + %d = %d\n", a, b, a + b);
    // Return result
    return 0;
}

(3) Width and Alignment

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // I/O operation
    printf("[%5d]\n", 42);
    // I/O operation
    printf("[%-5d]\n", 42);
    // I/O operation
    printf("[%05d]\n", 42);
    // Return result
    return 0;
}
TEXT
[   42]
[42   ]
[00042]

5. Escape Characters

Some characters can't be typed directly in a string (like newline or tab), so they're represented by escape characters starting with a backslash \:

Escape Meaning Example
\n Newline printf("A\nB") prints A and B on separate lines
\t Horizontal tab Commonly used for aligned output
\\ Literal backslash To print \, write \\
\" Double quote To print " inside a string
\' Single quote To print ' inside a character literal
\0 Null character Marks the end of a string
\r Carriage return Moves the cursor to the beginning of the line
\b Backspace Moves the cursor one position left
⚠️ Note: When printing file paths, you must use double backslashes:

C
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // I/O operation
    printf("C:\\Users\\admin\\file.txt\n");
    // Return result
    return 0;
}
TEXT
C:\Users\admin\file.txt

▶ Example: Escape Sequences in Action

▶ Try it Yourself
TEXT
Line one
Line two
Name	Age
Path: C:\code\hello.c
Quote: "Hello"

\n breaks a line, \t adds a tab, \\ prints a backslash, and \" prints a quote.

6. Comments

Comments are notes for humans — the compiler completely ignores them. Good comments make code easier to understand.

(1) Single-Line Comments

C99 introduced // style single-line comments. Everything from // to the end of the line is a comment:

C
// A whole-line comment: the next line is the actual code
// Variable declaration
int score = 100;  // Trailing comment: full marks

(2) Multi-Line Comments

/* */ style comments can span multiple lines:

C
/*
 * This program calculates
 * the sum of two numbers
 */
// Preprocessor directive
#include <stdio.h>

// Function definition
int main(void) {
    // Variable declaration
    int a = 10;
    // Variable declaration
    int b = 20;
    // I/O operation
    printf("%d\n", a + b);
    // Return result
    return 0;
}

(3) Comment Best Practices

Comments should explain why (the reasoning), not what (the obvious). The code itself already tells you what — comments should supplement with design intent and decisions that the code can't express.

A good comment:

C
// Variable declaration
int max_retries = 3;  // Retry up to 3 times on transient network failures

An unnecessary comment (the code already explains everything):

C
// Variable declaration
int x = 10;  // Assign 10 to x
⚠️ Note: Multi-line comments cannot be nested. The following will cause a compilation error:

TEXT
/*
  /* nested comment */
*/

The inner */ prematurely closes the outer comment, leaving the remaining */ as a syntax error.


▶ Example: Line, Block, and Trailing Comments

▶ Try it Yourself
TEXT
area = 12.57

Comments never reach the executable and do not affect performance; they are for humans and your future self.

7. Identifiers and Keywords

(1) Identifier Naming Rules

Identifiers are names you create yourself (variable names, function names, etc.). They must follow these rules:

Legal names: age, student_name, _count, MAX_SIZE

Illegal names: 2name (starts with digit), my-age (contains hyphen), int (keyword)

(2) Naming Conventions

Style Format Use Case Example
snake_case lowercase + underscores Variable names, function names student_count
UPPER_CASE ALL CAPS + underscores Constants MAX_BUFFER_SIZE
CamelCase Capitalize each word Custom type names StudentInfo

C traditionally uses snake_case, unlike Java/C# which favor camelCase. The most important thing is consistency within a project.

(3) C99 Keywords

C99 has 37 keywords, all lowercase:

Category Keywords
Data Types char short int long float double void signed unsigned _Bool _Complex _Imaginary
Control Flow if else switch case default for while do break continue goto return
Storage Classes auto extern static register typedef inline
Structures struct union enum
Other const volatile sizeof restrict

You don't need to memorize these — they'll become second nature with practice. What matters is knowing that keywords cannot be used as identifiers.

▶ Example

Let's combine everything from this chapter into a program that demonstrates basic syntax:

▶ Try it Yourself
TEXT
=== Student Info ===
Name:	Alice
Age:	20
Score:	95.5
Grade:	A
====================

This program demonstrates: the #include preprocessor directive, the main function structure, printf formatted output, \n newline, \t tab alignment, and four common format specifiers (%d, %.1f, %c, %s).

Reference entries in this section: printf #include scanf int char short long float double void signed unsigned

❓ FAQ

Q Does every C statement need a semicolon?
A Yes for statements and declarations. Preprocessor directives, if/for/while headers, and the brace before a function body do not take one. A missing semicolon usually reports expected ';'.
Q Can I omit braces {}
A For a single statement, if/for/while allow it, but always writing braces prevents scope bugs when you add a line later. Function bodies and struct definitions always need braces.
Q What is the difference between printf and puts?
A puts prints a string and adds a newline; printf supports format specifiers such as %d, %.2f, and %s. Use printf for formatting and puts for plain strings.
Q Why does \n not create a new line?
A Check for \\n (a literal backslash) or a string split across lines. C strings cannot span lines; use \n or a trailing backslash to continue.
Q Do comments affect performance?
A No. Comments are removed during preprocessing and never reach the binary. Avoid using comments to disable large blocks, which can conflict with nested comments.
Q Can C identifiers use non-English characters?
A C99 allows some Unicode identifiers, but compiler and editor support varies. In practice use letters, digits, and underscores, and never start with a digit.
Q Is C case-sensitive? How many keywords are there?
A Yes: Main and MAIN are not main. C89 has 32 keywords, C99 adds 5, and later standards add more; keywords cannot be used as variable names.

📖 Summary

📝 Exercises

  1. Write a program that uses printf to display your own info card (name, age, hobby), using \t for alignment
  2. Write a program that uses a single printf call to output the following (using escape characters for newlines and tabs): Name Alice, Age 25, City London
  3. Intentionally write a nested multi-line comment in your code and observe the compiler's error message
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏