Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Basic Syntax

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:

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:

A more complex C program structure description (later chapters will explain each knowledge point in detail):

Example

#include   // 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 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

Macro definition

Function declaration

Main function

Variable Declaration

Statements and Expressions

Control Flow Statements

Function definition

The return Statement

Separators

Separators are used to separate statements, expressions, and code blocks, helping the compiler understand the structure of the program. Common separators include:

- 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. - Square 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:

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:

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:

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:


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: