C Basic Syntax

C language is a general-purpose programming language, widely used in fields such as system programming, embedded development, and high-performance computing.

C language has characteristics such as high efficiency, flexibility, and strong portability. It is the foundation of many other programming languages (such as C++, Java, Go) and remains the mainstream choice for operating systems, drivers, and low-level library development.

In C language, tokens are the basic building blocks of a program. The compiler performs lexical analysis on the source code, breaking the code into individual tokens. Tokens are the smallest meaningful units the compiler can recognize, and the entire C program is composed of these tokens.

Tokens in C language mainly include the following types:

  • Keywords: words reserved by the language with special meanings, such asint、if、return。
  • Identifiers: names defined by programmers, used for variables, functions, arrays, etc.
  • Constants: Values in a program that are fixed and unchanged, such as integers42, floating-point numbers3.14。
  • String Literals: character sequences 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 language program that can output "Hello, World!":

Example

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}

The above code consists of the following structure:

  • Preprocessor directives: such as#includeand#define, processed by the preprocessor before compilation.
  • main function: every C program has one and only onemain()The function is the entry point of the program.
  • Variable declaration: declares the variables used in the program. C89 requires declarations to be at the very beginning of a code block.
  • Function definition: defines the functions used in the program, describing the specific implementation logic of the functions.

A more complex explanation of C program structure (each knowledge point will be elaborated in later chapters):

Example

#include <stdio.h> // Header file inclusion

#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 the results
    printf("Sum: %d\n", sum);

    return 0;        // Returning 0 indicates successful program execution
}

// Function definition
int add(int a, int b) {
    return a + b;
}

Header file inclusion

  • Header files are usually used at the beginning of a program#includeThe include directive. Header files provide declarations of functions and libraries, such as the standard input/output library<stdio.h>, standard library<stdlib.h>etc. They define functions, macros, constants, etc., enabling the program to use predefined library functions.
  • System header files use angle brackets<>, custom header files use double quotes"", the two have different search paths.
  • Example:#include <stdio.h>(system header files),#include "myheader.h"(custom header files)

Macro definition

  • A macro is implemented by#defineSymbolic constants or code snippets defined by directives. Macros are textually replaced by the preprocessor before compilation, do not occupy runtime memory, and are often used to define constants or simple inline code logic.
  • Macros have no type checking and should be used with caution; for constants with type requirements, it is recommended to useconstvariable substitution.
  • Example:#define PI 3.14159、#define MAX(a, b) ((a) > (b) ? (a) : (b))

Function Declaration

  • In C language, function declarations (also called prototypes) must appear before the function definition or call. The declaration provides the function's return type, function 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()The function is the entry point of a C program. Every C program must contain amain()function. The program starts frommain()starts execution, the return value is usually0indicates successful program execution, and a non-zero value indicates an error occurred.
  • main()Functions can also receive command-line arguments:int main(int argc, char *argv[]), whereargcis the number of parameters,argvis the argument string array.
  • Example:int main() { ... }

Variable declaration

  • In C programs, all variables must have their types declared before use. Variables can bemain()declared inside functions (local variables), or globally outside functions (global variables).
  • Variables can be initialized at the same time as declaration. Uninitialized local variables contain indeterminate values (garbage values), while global variables and static variables are automatically initialized to0。
  • Example:int count = 0;、float price = 9.99;、char grade = 'A';

statements and expressions

  • Statements are the basic execution units of a C program. They are usually function calls, assignments, and control statements (such asif、foretc.) or expressions. An expression is a code fragment composed of variables, operators, and constants that can compute a value.
  • In C language, assignment itself is also an expression and has a value (i.e., the assigned value), so you can writea = b = c = 0;chained assignment like this.
  • 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 branching (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 programs with clear logic, and their abuse should be avoided.gototo maintain code readability.
  • Example:
    if (num1 > num2) {
        printf("num1 is greater than num2");
    }

Function definition

  • A function definition contains a complete function body and describes the specific implementation of the function. 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.
  • C language functions do not support overloading. Each function name must be unique in the same scope. Functions can call themselves recursively.
  • Example:
    int add(int a, int b) {
        return a + b;
    }

Return statement

  • returnThe statement is used to terminate the execution of a function and return control, along with the return value, to the caller.voidFunctions of type can use a return without a valuereturn;to exit early, or can omitreturnstatement.
  • main()The return value of the function is passed to the operating system,0usually indicates success, and the standard macro can be usedEXIT_SUCCESSandEXIT_FAILURE(defined in<stdlib.h>)。
  • Example:return 0;、return EXIT_SUCCESS;

Delimiters

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 initialization lists.
  • Semicolon;: used to terminate a statement, and is the most common separator in C language.
  • Brackets:
    • Parentheses(): used for the parameter lists of function calls, conditions in control flow statements, and forcing expression evaluation order.
    • Curly braces{}: used to define function bodies, control-flow code blocks, and initializations of compound literals and arrays/structures.
    • Square brackets[]: used for array declarations and element access (subscript operation).

In C programs, the semicolon;is the statement terminator. Every statement must end with a semicolon, which indicates 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 be used as an empty statement, meaning it does nothing. It is often used in certain loop structures:

while (condition);  // 空循环体,等待条件变化

Comments

C language has two ways of commenting:

// Single-line comment

with//Single-line comments starting with (introduced by C99). This type of comment extends from//to the end of the line. It can occupy a line by itself or be placed at the end of a code line.

/* Single-line comment */
/* 
 Multi-line comment
 Multi-line comment
 Multi-line comment
 */

/* */Comments in this 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;
}

When using comments, note the following points:

  • Comments cannot be nested inside comments (/* /* */ */is illegal).
  • Comments cannot appear inside string literals or character constants.
  • Comments are written for people to read. They should be concise and clear, focusing on explaining "why" rather than "what was done"; the code itself should express "what it does."
  • Good commenting habits are an important part of professional programming, aiding code maintenance and team collaboration.

Identifiers

Identifiers are the names of variables, functions, arrays, types, etc., in a program, defined by the programmer. Identifiers consist of letters (uppercase or lowercase), digits, and underscores, but the first character must be a letter or underscore, not a digit.

An identifier starts 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 is aCase Sensitiveprogramming language. Therefore, in C,Manpowerandmanpowerare two different identifiers. Listed below are some valid identifiers:

mohd       zara    abc   move_name  a_123
myname50   _temp   j     a23b9      retVal

Below 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 underscore naming (my_variable) and lower camel case naming (myVariable), just keep it consistent within the same project. Identifiers beginning with double underscores__are usually reserved by the compiler or standard library and should be avoided in user code.

Constants

Constants are fixed values that do not change during program execution. There are two main ways to define constants in C: usingconstkeyword or use#defineMacro 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 (end-of-string marker)

UsageconstConstants defined with have type information, so the compiler can perform type checking. Compared with#defineMacros are safer and are the recommended approach in C99 and later.

string literal

String literals are character sequences enclosed in double quotes, used to represent text data.

String literals are stored in memory as character arrays, and a null character is automatically added at the end\0(i.e., the null terminator), marking the end of the string.

char greeting[] = "Hello, World!";  // 编译器自动计算长度(包含 \0)

Here 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 read-only memory 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!"Equivalent to"Hello, World!"。
  • Character'A'(character constants) and strings"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, form expressions, and produce results.

C language has a wide variety of operators. Common ones include:

  • Arithmetic Operators:+, -, *, /, %(where/performs integer division on integers,%remainder)
  • Relational Operators:==, !=, >, <, >=, <=(returns 1 for true, 0 for false)
  • Logical Operators:&&(AND),||(OR),!(NOT), supports short-circuit evaluation
  • Bitwise Operators:&(bitwise AND),|(bitwise OR),^(bitwise XOR),~(bitwise NOT),<<(left shift),>>(right shift)
  • Assignment Operators:=, +=, -=, *=, /=, %=(compound assignment, such asa += bEquivalent toa = a + b)
  • Increment/decrement operator:++(increment),--(decrement), which has two forms: prefix (decrement first, then evaluate) and postfix (evaluate first, then decrement)
  • Other Operators:sizeof(computes the byte size of a type or variable),?:(ternary operator),&(address-of),*(dereference),->(access members via pointer),.(direct member access)
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 evaluation direction for operators at the same level. When unsure about precedence, it is recommended to use parentheses for explicit grouping to improve code readability.

Keywords

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 language.

Keywords Description
autoDeclares automatic variables (the default storage class for local variables, rarely explicitly used in modern C)
breakBreaks out of the current loop or switch statement
caseBranch label in a switch statement
charDeclares a character-type variable or function return type (usually occupies 1 byte)
constDefines a read-only constant; the value of a variable modified by const can no longer be changed
continueEnds the current loop iteration and directly starts the next loop cycle
defaultDefault branch in a switch statement (executed when no case matches)
doThe loop body of the do-while loop; the loop body executes at least once
doubleDeclares a double-precision floating-point variable or function return type (usually occupies 8 bytes)
elseThe negative branch of a conditional statement (used with if)
enumDeclares an enumeration type, used to define a set of named integer constants
externDeclares that a variable or function is defined in another file or elsewhere in the current file
floatDeclares a single-precision floating-point variable or function return type (usually occupies 4 bytes)
forThe for loop statement, suitable for scenarios where the number of loop iterations is known in advance
gotoUnconditional jump statement (should be used with caution; may reduce code readability)
ifconditional statement
intDeclares an integer variable or function return type (usually occupies 4 bytes)
longDeclares a long integer variable or function return type
registerSuggests the compiler store the variable in a register to improve access speed (modern compilers usually optimize automatically)
returnFunction return statement, with or without a return value (void functions)
shortDeclares a short integer variable or function return type (usually occupies 2 bytes)
signedDeclares a signed type variable (can represent negative numbers; integers are signed by default)
sizeofComputes the number of bytes occupied by a data type or variable (compile-time operator)
staticDeclares static variables (local static variables have a lifetime extending to the end of the program; global static variables are limited to file scope)
structDeclares a structure type, combining data of different types into a whole
switchMulti-branch selection statement, jumps to the corresponding case based on the value of the expression
typedefDefines a new alias for an existing data type to improve code readability
unsignedDeclares an unsigned type variable (can only represent non-negative numbers, with a larger range)
unionDeclares a union type, all members share the same memory space
voidDeclares a function with no return value or no parameters; also used to declare a typeless pointervoid*
volatileDeclares that a variable may be changed by external factors (such as hardware or interrupts), prohibiting the compiler from optimizing reads and writes of the variable
whilewhile loop statement, suitable for scenarios where the number of iterations is unknown but the termination condition is clear

New keywords in C99

_Bool _Complex _Imaginary inline restrict

The keyword added in C99 is 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 keyword added in C11 is mainly used for: memory alignment control (_Alignas、_Alignof), atomic operations and multithreading support (_Atomic、_Thread_local), generic selection (_Generic), static assertion (_Static_assert) and marking functions with no return value (_Noreturn)。


Whitespace in C

A line containing only spaces is called a blank line; it may contain a comment, and the C compiler will completely ignore it.

In C, spaces are used to describe whitespace (space key), tab (Tab), newline, and comments. Spaces separate the parts of a statement, allowing the compiler to identify where an element in the statement (such asint) ends and where the next element begins. Therefore, in the following statement:

int age;

intandageThere must be at least one space character (usually a whitespace) between them so that the compiler can distinguish them. On the other hand, in the following statement:

fruit = apples + oranges;   // 获取水果的总数

fruitand=, or=andapplesThe space character between them is not required, but to enhance readability, you can add some spaces as needed.

Good spacing and indentation habits are an important part of high-quality code; it is recommended to follow the following conventions:

  • Use consistent indentation (usually 4 spaces or 1 tab) to indicate code block hierarchy.
  • Add spaces on both sides of operators (e.g.a + b), making expressions easier to read.
  • Add a space after commas (e.g.int a, b, c;), to distinguish multiple elements.
  • Use blank lines appropriately to separate logically related code sections, improving overall readability.
other extensions