C Variable

Variables are actually just names for the storage areas that a program can operate on. In C, every variable has a specific type, which determines the size and layout of the variable's storage. Values within that range can be stored in memory, and operators can be applied to the variable.

Variable names can consist of letters, digits, and underscore characters. They must begin with a letter or underscore. Uppercase and lowercase letters are different because C is case-sensitive. Based on the basic types explained in the previous chapter, there are the following basic variable types:

TypeDescription
charUsually one byte (eight bits). This is an integer type.
intInteger, 4 bytes, value range from -2147483648 to 2147483647.
float

Single-precision floating-point value. Single-precision has the format: 1 sign bit, 8 exponent bits, and 23 fraction bits.

double

Double-precision floating-point value. Double-precision has 1 sign bit, 11 exponent bits, and 52 fraction bits.

voidIndicates the absence of a type.

The C language also allows defining various other types of variables, such as enums, pointers, arrays, structures, unions, and so on. These will be explained in later chapters. In this chapter, we first discuss the basic variable types.

Variable definitions in C

Variable definition tells the compiler where and how to create storage for a variable. A variable definition specifies a data type and contains a list of one or more variables of that type, as shown below:

type variable_list;

typeIndicates the data type of the variable. It can be integer, floating-point, character, pointer, etc., and it can also be a user-defined object.

variable_listCan consist of one or more variable names, with multiple variables separated by commas.,Separated. Variables consist of letters, digits, and underscores, and begin with a letter or underscore.

Below are several valid declarations:

Define integer variable:

int age;

In the above code, age is defined as an integer variable.

Define a floating-point variable:

float salary;

In the above code, salary is defined as a floating-point variable.

Define a character variable:

char grade;

In the above code, grade is defined as a character variable.

Define pointer variable:

int *ptr;

In the above code, ptr is defined as an integer pointer variable.

Define multiple variables:

int    i, j, k;

int i, j, k;Declared and defined the variablei, j and k, which instructs the compiler to create a variable of typeintnamedi、j、kvariable.

Variable initialization

In the C language, variable initialization is assigning an initial value to a variable at the same time as defining it. The initialization of a variable can be done at the time of definition, or in subsequent code.

An initializer consists of an equals sign followed by a constant expression, as shown below:

type variable_name = value;

where,typeindicates the data type of the variable,variable_nameis the name of the variable,valueis the initial value of the variable.

Here are a few examples:

int x = 10;         // 整型变量 x 初始化为 10
float pi = 3.14;    // 浮点型变量 pi 初始化为 3.14
char ch = 'A';      // 字符型变量 ch 初始化为字符 'A'
int d = 3, f = 5;           // 定义并初始化 d 和 f
byte z = 22;                // 定义并初始化 z

// 声明外部变量
extern int d;
extern int f;

To initialize the variable later:

In the code after the variable definition, the assignment operator can be used.=Assign a new value to the variable.

type variable_name;    // 变量定义
variable_name = new_value;    // 变量初始化

Example as follows:

int x;          // 整型变量x定义
x = 20;         // 变量x初始化为20
float pi;       // 浮点型变量pi定义
pi = 3.14159;   // 变量pi初始化为3.14159
char ch;        // 字符型变量ch定义
ch = 'B';       // 变量ch初始化为字符'B'

Note that variables should be initialized before use. The value of an uninitialized variable is undefined and may contain arbitrary garbage values. Therefore, to avoid undefined behavior and errors, it is recommended to initialize variables before using them.

Variable not initialized

In the C language, if a variable is not explicitly initialized, its default value depends on the variable's type and its scope.

For global variables and static variables (static variables defined inside functions and global variables defined outside functions), their default initial value is zero.

The following are the default values for different types of variables when they are not explicitly initialized:

  • Integer variables (int, short, long, etc.): default value is 0.
  • Floating-point variables (float, double, etc.): default value is 0.0.
  • Character variable (char): the default value is '\0', i.e., the null character.
  • Pointer variable: the default value is NULL, meaning the pointer does not point to any valid memory address.
  • Variables of composite types such as arrays, structures, and unions: their elements or members will be default-initialized according to the corresponding rules, which may include recursively applying the default rules to elements.

Note that local variables (non-static variables defined inside functions) are not automatically initialized to default values; their initial values are undefined (contain garbage values). Therefore, before using a local variable, you should explicitly assign an initial value to it.

In summary, the default value of a variable in C depends on its type and scope. The default value for global variables and static variables is0, the default value of a character variable is\0, the default value for pointer variables is NULL, and local variables have no default value; their initial values are undefined.

Variable declarations in C

A variable declaration assures the compiler that a variable exists with the specified type and name, so that the compiler can continue further compilation without needing to know the full details of the variable. A variable declaration only has meaning at compile time; when the program is linked, the compiler needs the actual variable declaration.

There are two cases of variable declarations:

  • 1. One kind requires storage space to be created. For example:int aStorage space is already established at the time of declaration.
  • 2. The other kind does not require storage space to be created, by using the extern keyword to declare a variable name without defining it. For example:extern int awhere variablesacan be defined in another file.

Unless there isexternkeyword; otherwise, they are all variable definitions.

extern int i; //声明,不是定义
int i; //声明,也是定义

For more explanation on extern, see:C extern keyword。

Example

Try the following example, where variables are declared at the top, but defined and initialized in the main function:

Example

#include <stdio.h> // Define variables x and y outside the function int x; int y; int addtwonum() { // Declare variables x and y as external variables inside the function extern int x; extern int y; // Assign values to external variables (global variables) x and y x = 1; y = 2; return x+y; } int main() { int result; // Call the function addtwonum result = addtwonum(); printf("result is: %d",result); return 0; }

When the above code is compiled and executed, it produces the following results:

result 为: 3

If you need to reference a variable defined in another source file, you only need to add the extern keyword declaration to that variable in the file referencing it.

Code of the addtwonum.c file:

#include <stdio.h> /*External variable declaration*/ extern int x ; extern int y ; int addtwonum() { return x+y; }

Code of the test.c file:

#include <stdio.h> /*Define two global variables*/ int x=1; int y=2; int addtwonum(); int main(void) { int result; result = addtwonum(); printf("result is: %d\n",result); return 0; }

When the above code is compiled and executed, it produces the following results:

$ gcc addtwonum.c test.c -o main
$ ./main
result 为: 3

Lvalues and Rvalues in C

There are two types of expressions in C:

  1. lvalue:An expression that points to a memory location is called an lvalue expression. An lvalue can appear on either the left or the right side of an assignment operator.
  2. rvalue:The term rvalue refers to a value stored at some address in memory. An rvalue is an expression that cannot be assigned to; that is, an rvalue can appear on the right side of an assignment operator, but cannot appear on the left side.

Variables are lvalues, so they can appear on the left side of an assignment operator. Numeric literals are rvalues, so they cannot be assigned to and cannot appear on the left side of an assignment operator. The following is a valid statement:

int g = 20;

But the following is not a valid statement and will generate a compile-time error:

10 = 20;
other extensions