C Basic Syntax
C is a general-purpose programming language widely used in areas such as systems programming, embedded development, and high-performance computing.
C features high efficiency, flexibility, and strong portability, and is the foundation of many other programming languages (such as C++, Java, and Go). It remains a mainstream choice for developing operating systems, drivers, and low-level libraries.
In C, a token is the basic unit of a program. The compiler performs lexical analysis on the source code, breaking the code into individual tokens. A token is the smallest meaningful unit that the compiler can recognize, and the entire C program is composed of these tokens.
The tokens in C mainly include the following types:
- Keywords: words reserved by the language with special meanings, such as
int,if,return. - Identifiers: names defined by the programmer, used for variables, functions, arrays, etc.
- Constants: values that remain fixed in a program, such as integers
42, floating-point numbers3.14. - String Literals: sequences of characters enclosed in double quotes, such as
"Hello". - Operators: symbols used to perform operations, such as
+,==,&&. - Separators: symbols used to separate statements and code blocks, such as
;,{}.
Basic Structure of a C Program
This is a simple C program that can print "Hello, World!":
Example
#include
int
main
(
)
{
printf
(
"Hello, World!\n"
)
;
return
0
;
}
The structure of the code above is as follows:
- Preprocessor directives: Such as
#includeand#define, processed by the preprocessor before compilation. - Main function: Every C program has one and only one
main()function, which is the entry point of the program. - Variable Declaration: declare the variables used in the program; C89 requires declarations to be at the very beginning of a code block.
- Function definition: define the functions used in the program, describing their specific implementation logic.
A more complex C program structure description (later chapters will explain each knowledge point in detail):
Example
#include
#define PI 3.14159 // Macro definition
// Function declaration
int
add
(
int
a,
int
b
)
;
int
main
(
)
{
// Main function
// variable declaration
int
num1, num2, sum
;
// User input
printf
(
"Enter two integers: "
)
;
scanf
(
"%d %d"
,
&
num1,
&
num2
)
;
// function call
sum
=
add
(
num1, num2
)
;
// Output result
printf
(
"Sum: %d\n"
, sum
)
;
return
0
;
// Returning 0 indicates the program executed successfully
}
// Function definition
int
add
(
int
a,
int
b
)
{
return
a
b
;
}
Header file inclusion
- Header files are usually included at the beginning of a program using
#includethe directive. Header files provide declarations of functions and libraries, such as the standard input/output library, the standard library, etc. They define functions, macros, constants, and so on, enabling the program to use predefined library functions. - System header files use angle brackets
<>, while custom header files use double quotes"", and the two have different search paths. - Example:
#include(system header files),#include "myheader.h"(custom header files)
Macro definition
- A macro is a symbolic constant or code fragment defined through the
#definedirective. Macros are text-replaced by the preprocessor before compilation, occupy no runtime memory, and are often used to define constants or simple inline code logic. - Macros have no type checking, so use them with caution; for constants that require a type, it is recommended to use
constvariables instead. - Example:
#define PI 3.14159,#define MAX(a, b) ((a) > (b) ? (a) : (b))
Function declaration
- In C, a function declaration (also called a prototype) must appear before the function is defined or called. The declaration provides the function's return type, name, and parameter list so that the compiler can perform type checking at the call site.
- Function declarations can be placed in header files for sharing among multiple source files.
- Example:
int add(int a, int b);
Main function
main()A function is the entry point of a C program, and every C program must contain amain()function. The program begins execution frommain(), and the return value is usually0indicating successful execution, while a nonzero value indicates an error.main()Functions can also receive command-line arguments:int main(int argc, char *argv[]), whereargcis the number of arguments,argvis an array of argument strings.- Example:
int main() { ... }
Variable Declaration
- In C programs, all variables must have their types declared before use. Variables can be declared
main()inside a function (local variables) or globally outside a function (global variables). - Variables can be initialized at the time of declaration. Uninitialized local variables contain indeterminate values (garbage values), while global and static variables are automatically initialized to
0. - Example:
int count = 0;,float price = 9.99;,char grade = 'A';
Statements and Expressions
- A statement is the basic execution unit of a C program, typically a function call, an assignment, a control statement (such as
if,for, etc.) or an expression. An expression is a code fragment composed of variables, operators, and constants that can be evaluated to a value. - In C, assignment is itself an expression with a value (the value assigned), so you can write
a = b = c = 0;such chained assignments. - Example:
printf("Enter two integers: "); sum = add(num1, num2);
Control Flow Statements
- Control flow statements are used to control the order of program execution, including conditional judgments (
if/else,switch) and loops (for,while,do-while). There are also jump statementsbreak,continue,gotoandreturn. - Using control flow statements reasonably is the key to writing logically clear programs; one should avoid abusing
gototo maintain code readability. - Example:
if (num1 > num2) { printf("num1 is greater than num2"); }
Function definition
- A function definition contains the complete function body and describes the specific implementation. A function consists of a return type, function name, parameter list, and function body. Good function design should follow the "single responsibility" principle, with each function doing only one thing.
- Functions in C do not support overloading; each function name must be unique within the same scope. A function can call itself recursively.
- Example:
int add(int a, int b) { return a + b; }
The return Statement
returnThe statement is used to terminate the execution of a function and hand control back to the caller along with a return value.voidFunctions of this type can exit early by using a return without a valuereturn;, or the return statement can be omittedreturnif statement.main()The return value of a function is passed to the operating system,0where it usually indicates success. You can use the standard macroEXIT_SUCCESSandEXIT_FAILURE(defined in).- Example:
return 0;,return EXIT_SUCCESS;
Separators
Separators are used to separate statements, expressions, and code blocks, helping the compiler understand the structure of the program. Common separators include:
- Comma ,: used to separate multiple elements in variable declarations, function parameters, or initializer lists.
- Semicolon ;: used to terminate a statement; it is the most common separator in C.
- Bracket:
- Parentheses
(): used for the argument lists of function calls, the conditions of control flow statements, and to force the evaluation order of expressions. - Curly braces
{}: used to define function bodies, control flow code blocks, and the initialization of compound literals and arrays/structs. - Brackets
[]: used for array declarations and element access (subscript operations).
In C, the semicolon ; is the statement terminator; every statement must end with a semicolon, which marks the end of a logical entity. A missing semicolon is one of the most common syntax errors for beginners.
For example, the following are two different statements:
printf("Hello, World! \n");
return 0;
A single semicolon can also serve as an empty statement, meaning "do nothing", often used in certain loop constructs:
while (condition); // 空循环体,等待条件变化
Notes
C has two ways to write comments:
// single-line comment
Single-line comments starting with // (introduced in C99); such a comment begins with // and ends at the end of the line. It can occupy a whole line by itself or be placed at the end of a code line.
/* Single-line comment */
/*
多行注释
多行注释
多行注释
*/
Comments in the /* */ format can be single-line or multi-line, suitable for longer comment scenarios such as function descriptions and module headers.
Example
// This is a single-line comment
/*
This is a multi-line comment
It can span multiple lines
*/
int
main
(
)
{
// Print a message
printf
(
"Hello, World!\n"
)
;
return
0
;
}
Note the following points when using comments:
- Comments cannot be nested inside comments (
/* /* */ */is invalid). - Comments cannot appear inside string literals or character constants.
- Comments are written for people and should be concise and clear, focusing on explaining "why" rather than "what". The code itself should express "what".
- Good commenting habits are an important part of professional programming, helping with code maintenance and team collaboration.
Identifiers
Identifiers are the names of variables, functions, arrays, types, etc. in a program, defined by the programmer. An identifier consists of letters (uppercase or lowercase), digits, and underscores, but the first character must be a letter or an underscore, not a digit.
An identifier begins with a letter A-Z or a-z or an underscore _, followed by zero or more letters, underscores, and digits (0-9).
Punctuation characters such as @, $, and % are not allowed in C identifiers. C isCase Sensitivityprogramming language. Therefore, in C,Manpower and manpower are two different identifiers. Several valid identifiers are listed below:
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal
The following are some examples of invalid identifiers and the reasons:
2abc // 错误:以数字开头
my-name // 错误:包含连字符 -
float // 错误:与关键字重名
my name // 错误:包含空格
Naming suggestions: identifiers should be descriptive and clearly express their purpose. Common naming styles include snake_case (my_variable) and lowerCamelCase (myVariable); just keep it consistent within the same project. Identifiers beginning with a double underscore __ are usually reserved by the compiler or standard library and should be avoided in user code.
Constant
Constants are fixed values that do not change during program execution. There are two main ways to define constants in C: using the const keyword or using #define a macro definition.
Constants can be integer constants, floating-point constants, character constants, enumeration constants, etc.:
const int MAX = 100; // 整型常量
const float PI = 3.14159; // 浮点型常量
const char NEWLINE = '\n'; // 字符常量(转义字符)
Common escape characters in character constants include:
\n: Newline\t: horizontal tab\\Backslash\': single quote\0: null character (string terminator)
Use const Constants defined with have type information, and the compiler can perform type checking, making them safer than #define macros; this is the recommended approach in C99 and later.
String Literals
A string literal is a sequence of characters enclosed in double quotes, used to represent text data.
A string literal is stored in memory as a character array, with a null character \0 (i.e., the null terminator) automatically appended at the end to mark the end of the string.
char greeting[] = "Hello, World!"; // 编译器自动计算长度(包含 \0)
The following are some important notes about string literals:
- "Hello" actually occupies 6 bytes in memory:
'H'、'e'、'l'、'l'、'o'、'\0'. - String literals are stored in a read-only memory area and cannot be modified; if modification is needed, they should be copied into a character array.
- Two adjacent string literals are automatically concatenated by the compiler:
"Hello, " "World!"is equivalent to"Hello, World!". - Character
'A'(character constant) and the string"A"(string literal) are different; the latter contains'A'and'\0'two characters.
Operators
Operators are used to perform various operations, such as arithmetic, logical, and comparison operations. Operators act on operands to form expressions and produce results.
There are many kinds of operators in C; common ones include:
- Arithmetic operators:
+,-,*,/,%(where/performs integer division on integers,%takes the remainder) - Relational operators:
==,!=,>,<,>=,<=(returns 1 for true and 0 for false) - Logical operators:
&&(AND),||(OR),!(NOT), supporting short-circuit evaluation - Bitwise operators:
&(bitwise AND),|(bitwise OR),^(bitwise XOR),~(bitwise NOT),<<(left shift),>>(right shift) - Assignment operators:
=,+=,-=,*=,/=,%=(compound assignment, such asa += bis equivalent toa = a + b) - Increment/Decrement Operators:
++(increment),--(decrement), with two forms: prefix (operate first, then take the value) and postfix (take the value first, then operate) - Other operators:
sizeof(compute the byte size of a type or variable),?:(ternary operator),&(address-of),*(dereference),->(access a member through a pointer),.(access a member directly)
int a = 5, b = 10;
int sum = a + b; // 算术运算符 +,sum = 15
int isEqual = (a == b); // 关系运算符 ==,isEqual = 0(假)
int result = a << 1; // 位运算左移,result = 10(相当于 a * 2)
a++; // 后缀自增,a 变为 6
int max = (a > b) ? a : b; // 三目运算符,max = b = 10
Operators have precedence and associativity: precedence determines the order of operations, and associativity determines the direction in which operators of the same precedence are evaluated. When unsure about precedence, it is recommended to use parentheses to make grouping explicit and improve code readability.
The keyword
The following table lists the reserved words in C. These reserved words cannot be used as constant names, variable names, or other identifier names; they have specific syntactic meanings in C.
| The keyword | Description |
|---|---|
| auto | Declare automatic variables (the default storage class for local variables, rarely used explicitly in modern C) |
| break | Exit the current loop or switch statement |
| case | A branch label in a switch statement |
| char | Declare character-type variables or function return types (usually 1 byte) |
| const | Define a read-only constant; the value of a variable modified by const cannot be changed |
| continue | End the current loop iteration and start the next one directly |
| default | The default branch in a switch statement (executed when no case matches) |
| do | The body of a do-while loop, which executes at least once |
| double | Declare double-precision floating-point variables or function return types (usually 8 bytes) |
| else | The negative branch of a conditional statement (used with if) |
| enum | Declare an enumeration type, used to define a set of named integer constants |
| extern | Declare that a variable or function is defined in another file or elsewhere in the same file |
| float | Declare single-precision floating-point variables or function return types (usually 4 bytes) |
| for | The for loop statement, suitable for cases where the number of iterations is known |
| goto | An unconditional jump statement (use with caution, as it may reduce code readability) |
| if | Conditional statement |
| int | Declare integer variables or function return types (usually 4 bytes) |
| long | Declare long integer variables or function return types |
| register | Suggest that the compiler store a variable in a register to improve access speed (modern compilers usually optimize automatically) |
| return | The function return statement, which may or may not carry a return value (for void functions) |
| short | Declare short integer variables or function return types (usually 2 bytes) |
| signed | Declare signed type variables (can represent negative numbers; integers are signed by default) |
| sizeof | Compute the number of bytes occupied by a data type or variable (a compile-time operator) |
| static | Declare static variables (the lifetime of local static variables extends to the end of the program; global static variables are restricted to file scope) |
| struct | Declare a structure type, combining different types of data into a whole |
| switch | A multi-branch selection statement that jumps to the corresponding case based on the value of an expression |
| typedef | Define a new alias for an existing data type to improve code readability |
| unsigned | Declare unsigned type variables (can only represent non-negative numbers, with a larger range) |
| union | Declare a union type, in which all members share the same memory space |
| void | Declare that a function has no return value or no parameters; also used to declare a typeless pointer void* |
| volatile | Declare that a variable may be changed by factors outside the program (such as hardware or interrupts), preventing the compiler from optimizing reads and writes of that variable |
| while | The while loop statement, suitable for cases where the number of iterations is unknown but the termination condition is clear |
New Keywords in C99
| _Bool | _Complex | _Imaginary | inline | restrict |
|---|
The new keywords in C99 are mainly used for: Boolean type support (_Bool), complex number support (_Complex, _Imaginary), inline function optimization (inline), pointer alias restriction optimization (restrict).
New Keywords in C11
| _Alignas | _Alignof | _Atomic | _Generic | _Noreturn |
|---|---|---|---|---|
| _Static_assert | _Thread_local |
The new keywords in C11 are mainly used for: memory alignment control (_Alignas, _Alignof), atomic operations and multithreading support (_Atomic, _Thread_local), generic selection (_Generic), static assertions (_Static_assert) and marking functions that do not return a value (_Noreturn).
Whitespace in C
A line containing only whitespace is called a blank line; it may contain a comment, and the C compiler ignores it completely.
In C, whitespace refers to blank characters (space), tabs, newlines, and comments. Whitespace separates the parts of a statement, allowing the compiler to recognize where a certain element in a statement (such as int) ends and where the next element begins. Therefore, in the following statement:
int age;
int and age there must be at least one space character (usually a whitespace character) between them so that the compiler can distinguish them. On the other hand, in the following statement:
fruit = apples + oranges; // 获取水果的总数
fruit and =, or = and apples the space characters between them are not required, but to enhance readability you can add some spaces as needed.
Good whitespace and indentation habits are an important part of high-quality code; it is recommended to follow these guidelines:
- Use consistent indentation (usually 4 spaces or 1 tab) to indicate code block levels.
- Add spaces on both sides of operators (such as
a + b) to make expressions more readable. - Add a space after commas (such as
int a, b, c;) to distinguish multiple elements. - Use blank lines appropriately to separate logically related code segments and improve overall readability.