Basic Syntax

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.

Program Structure

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

C
#include <stdio.h>

int main(void) {
    return 0;
}

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

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)

The main Function

C
int main(void) {
    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.

Other Forms of main

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

C
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).

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
int age = 18;
age = age + 1;
printf("I am %d years old\n", age);

Each line is a statement, ending with a semicolon.

A common mistake — forgetting the semicolon:

C
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
int age = 18; age = age + 1; printf("%d\n", age);

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.

Code Blocks

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

C
int main(void) {
    int x = 10;
    int y = 20;
    int sum = x + y;
    printf("Sum = %d\n", sum);
    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
int main(void) {
    int a = 1;
    {
        int b = 2;
        printf("a + b = %d\n", a + b);
    }
    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.

The printf Function

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

Basic Usage

C
printf("Hello, World!\n");

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

Format Specifiers

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

C
int age = 18;
float height = 1.75f;
char grade = 'A';
printf("Age: %d\n", age);
printf("Height: %.2f\n", height);
printf("Grade: %c\n", grade);

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
int a = 3, b = 4;
printf("%d + %d = %d\n", a, b, a + b);

Width and Alignment

C
printf("[%5d]\n", 42);
printf("[%-5d]\n", 42);
printf("[%05d]\n", 42);
TEXT
[   42]
[42   ]
[00042]

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
printf("C:\\Users\\admin\\file.txt\n");
TEXT
C:\Users\admin\file.txt

Comments

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

Single-Line Comments

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

C
int score = 100;

Multi-Line Comments

/* */ style comments can span multiple lines:

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

int main(void) {
    int a = 10;
    int b = 20;
    printf("%d\n", a + b);
    return 0;
}

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
int max_retries = 3;

An unnecessary comment (the code already explains everything):

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

C
/*
  /* nested comment */
*/

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

Identifiers and Keywords

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)

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.

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:

C
#include <stdio.h>

int main(void) {
    printf("=== Student Info ===\n");
    printf("Name:\t%s\n", "Alice");
    printf("Age:\t%d\n", 20);
    printf("Score:\t%.1f\n", 95.5);
    printf("Grade:\t%c\n", 'A');
    printf("====================\n");
    return 0;
}
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).

❓ FAQ

Q Why does C use semicolons instead of line breaks to separate statements?
A Because C allows a single statement to span multiple lines and multiple statements on one line. Semicolons are more flexible as delimiters — the compiler doesn't need to care about how the code is formatted.
Q What does the 'f' in printf stand for?
A 'f' stands for "formatted." printf doesn't just print fixed text — it can insert variable values into the output using specifiers like %d and %f. That's what "formatted output" means.
Q Do too many comments slow down my program?
A Not at all. The compiler removes all comments during preprocessing, so the compiled executable contains zero comment content. Write as many comments as you like — they have no effect on performance.
Q Should I use void main or int main?
A Always use int main(void). The C standard explicitly requires main to return int. void main is a non-standard extension from some old compilers — modern compilers may warn about or even reject it.

📖 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
100%

🙏 帮我们做得更好

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

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