Menu Close

Memory and Variables in C Programming

1. Memory

In C programming, memory is an essential component that is used to store and manipulate data during program execution. Memory in C programming refers to the physical space in a computer’s memory where data and instructions are stored for processing.
C programming also provides pointers, which are variables that store memory addresses.

Pointers in C allow programmers to access and manipulate memory directly, enabling efficient memory management and more flexible programming.

Therefore, memory is a critical concept in C programming and plays a significant role in the performance and functionality of programs.

From a hardware perspective, memory is actually a component of a computer (generally called a memory module or RAM module). Depending on the different hardware implementation principles, memory can be divided into SRAM and DRAM (DRAM also has many generations, such as the earliest SDRAM, later DDR1, DDR2, LPDDR, etc.).

From a logical perspective, memory is a group of spaces that can be randomly accessed (random access means that as long as an address is given, the memory address can be accessed) and can be read and written (of course, logically, it can also be limited to read-only or write-only). In programming, memory is used to store variables (because there is memory, C language can define variables, and each variable in C language corresponds to a unit in memory).

Memory is actually composed of an infinite number of memory cells, each with a fixed address called a memory address. This memory address corresponds uniquely and permanently to the memory cell.

Variables in C language are identifiers used to store data of different types, such as integers, characters, floating-point numbers, etc. In C language, the value of a variable is stored in memory.

Memory is the place where the computer stores data and programs. Memory can be seen as a large array, with each unit having a unique address. Programs can access and manipulate data in memory by specifying memory addresses. In C language, variables are also stored in memory, and the variable name is actually an alias for the variable’s address in memory.

When a variable is declared in a program, the C compiler allocates a block of memory to store the variable’s value. The memory address of a variable can be obtained using the & operator. For example, in the following code:


int x = 10;

The variable x is allocated a 4-byte memory space, and its value is initialized to 10. The program can access the variable using x, or obtain the memory address of the variable using &x.

When a program reads or writes the value of a variable, it is actually accessing the variable’s location in memory. C language’s pointer type provides the ability to access memory directly, and programmers can use pointers to manipulate data in memory. For example, the following code uses a pointer to access the value and address of variable x:


int x = 10;
int *p = &x;
printf("The value of x is: %d\n", *p);
printf("The address of x is: %p\n", p);

In this code, the pointer p points to the memory address of variable x, and the program uses *p to get the value of variable x, and %p to print the memory address of variable x.

In summary, there is a close relationship between variables and memory in C language. Variables are stored in memory and accessed and manipulated through memory addresses. Programmers can use pointers to directly manipulate data in memory, thereby achieving more flexible and efficient program design.

2.Variables

A variable is a name given to a storage location used to store data,  is a fundamental element used to store data in a program.  Its value can be changed and can be reused multiple times. It is a method of representing a storage location through a symbol so that it can be easily identified.

To indicate the storage area, each variable should be given a unique name (identifier). Variable names are just the symbolic representation of a memory location. 

2.1. Declaring a Variable

2.1.1  Declaring a Variable

means “requesting a block of memory in the computer’s memory based on the data type”, and giving it a variable name.

Syntax


DataType VariableName ;

For Example:

double money;
int age;
boolean sex;
float score;

2.1.2 Assigning a Value to a Variable

means “storing data in the corresponding memory space”.

Syntax


VariableName = Value ;

For Example:

money = 20.5;
age = 18;
sex = true;
score = 80.8F;

The decomposition steps are a bit cumbersome. Alternatively, steps (2.1.1) and (2.1.2) can be combined into one step by declaring a variable and assigning a value to it at the same time.

Syntax


DataType VariableName = Value ;

For Example:

double money = 20.5;
int age = 18;
boolean sex = true;
float score = 80.8F;

Variable Declaration

Variable declaration in C tells the compiler about the existence of the variable with the given name and data type. No memory is allocated to a variable in the declaration.

Variable Definition

In the definition of a C variable, the compiler allocates some memory and some value to it. A defined variable will contain some random garbage value till it is not initialized.

Variable Initialization

Initialization of a variable is the process where the user assigns some meaningful value to the variable.

2.2 Rules for naming a variable

  • Variables can contain letters, numbers, and underscores
  • Variable names can start with a letter or underscores
  • It cannot start with a number.
  • Spaces are not allowed in variable names.
  • Variable names cannot be any reserved words or keywords such as int, float, etc.

2.2.1 Here are some examples of valid variable names:

  1. my_variable
  2. myVariable
  3. MyVariable
  4. MY_VARIABLE
  5. variable2
  6. variable_2
  7. _variable
  8. _myVariable
  9. count
  10. totalSum

2.2.2 Here are some examples of invalid variable names:

  1. 2variable (starts with a number)
  2. my variable (contains a space)
  3. my-variable (contains a hyphen)
  4. break (a reserved keyword)

Note that these are just some examples, there may be other invalid variable names as well. In general, variable names should be concise, clear, and descriptive. Additionally, avoid using reserved keywords or special characters.

Note that variable names are case-sensitive, so myVariable and myvariable are considered to be different variable names.

2.3. The Types of Variables in the C Language

here are several types of variables in C:

On the basis of scope, C variables can be classified into two types:

  1. Local Variables
  2. Global Variables

On the basis of storage classes, we can classify the C variables into 4 types:

  1. Static Variables
  2. Automatic Variables
  3. Extern Variables
  4. Register Variables

    2.3.1 Local Variables

    In C programming, a local variable is a variable that is declared inside a block of code such as a function, loop, or conditional statement. Local variables have a local scope, which means they can only be accessed and used within the block of code in which they are declared.

    Local variables are useful for storing temporary data that is only needed for a short period of time within a specific block of code. They are created when the block of code is entered and destroyed when the block of code is exited. This means that the memory used by local variables is automatically released when they are no longer needed, making the program more memory-efficient.

    The syntax for declaring a local variable is the same as declaring any other variable, with the added constraint that it must be declared within a block of code. For example:

    void myFunction() {
        int x; // This is a local variable
        x = 5; // Assign a value to x
        // ... Do something with x
    } // x is destroyed when the function exits
    

    Local variables can also be initialized with a value when they are declared, like this:

    void myFunction() {
        int x = 5; // Initialize x with the value 5
        // ... Do something with x
    } // x is destroyed when the function exits
    

    It is important to note that local variables cannot be accessed outside of the block of code in which they are declared. If you need to share data between different blocks of code, you will need to use global variables or pass the data as arguments to functions.

    2.3.2 Global Variables

    In C programming, a global variable is a variable that is declared outside of any function and any block, and is therefore accessible and usable from anywhere in the program. Global variables have a global scope, which means they can be accessed and modified by any function in the program, as long as the program includes the variable’s declaration.

    Global variables are useful for storing data that needs to be accessed by multiple functions or throughout the entire program. They can be used to share data between different parts of the program and avoid passing large amounts of data as function arguments.

    The syntax for declaring a global variable is similar to declaring any other variable, but it is placed outside of any function and any block. For example:

    int globalVariable ; // This is a global variable
    

    Global variables can also be initialized with a value when they are declared, like this:

    int globalVariable = 5; // Initialize the global variable with the value 5
    

    It is important to note that using global variables can make it more difficult to understand and maintain the program, because any function in the program can modify them. It is generally recommended to use global variables sparingly and only when necessary, in order to avoid potential issues with unintended side effects or conflicts with other parts of the program.

    2.3.3 Static Variables

    In C programming, a static variable is a variable that retains its value between function calls and has a local scope within a function. Unlike local variables, which are destroyed when a function exits, static variables are not destroyed and their values persist across multiple function calls.

    Static variables are declared using the static keyword before the variable declaration,

    Syntax:

    static DataType VariableName = Value;
    

    like this:

    void myFunction() {
       static int myStaticVariable = 0; // This is a static variable
       // Rest of function code...
    }
    

    When a function containing a static variable is called for the first time, the variable is initialized to its default value (usually 0), and its value is retained between subsequent function calls. This makes static variables useful for maintaining state or counting the number of times a function has been called, for example.

    One important thing to note is that static variables are local to the function in which they are declared, so they cannot be accessed or modified from outside that function. However, they retain their value across multiple function calls within the same program execution.

    Static variables can also be used outside of functions, in which case they have file scope and can be accessed from any function in the same file. In this case, the static keyword is used before the variable declaration outside of any function, like this:

    static int myStaticVariable = 0; // This is a static variable with file scope
    

    Overall, static variables are useful for maintaining state across function calls and for preventing unintended access or modification of variables from outside the intended scope.

    Example 2.3.1 The Application of static Variables

    int main ()
    {
        int x=10;   //local variable
        static int y=10;  //static variable
        x=x+1;
        y=y+1;
        printf("%d, %d", x, y);
    }
    

    If we change the main function to any other function, say “fun1()”, and if we call this function multiple times, then local variables will output the same value for each function call, such as 11, 11, 11, and so on.

    However, the value of static variables will increase in each function call and will display values like 11, 12, 13, and so on.

    3.4 Automatic Variables

    Automatic variables are local variables that are declared with the “auto” keyword within a block or function. They are automatically created and initialized every time the block or function is entered, and they are automatically destroyed when the block or function is exited.

    The scope of automatic variables is limited to the block or function in which they are declared, which means that they cannot be accessed from outside that block or function. Automatic variables are commonly used in C programming for storing temporary data that is only needed within a specific block or function.

    By default, all variables declared within a block in C are automatic variables. We can explicitly declare a variable as automatic using the “auto” keyword.

    Syntax:

    auto DataType VariableName;
    

    or

    DataType VariableName;    
    

     

    void main()
    {
        int x=10; //local variable (also automatic)
        auto int y=20; //automatic variable
    }
    

    3.5 Extern Variables

    In C programming, an extern variable is a global variable that is declared in one file but can be accessed in other files.

    When an extern variable is declared, it tells the compiler that the variable is defined in another file, and the compiler should not allocate memory for it. Instead, the linker resolves the reference to the variable by finding the actual definition of the variable in another file and linking it with the file that references it.

    To use an extern variable in a file, we need to declare it with the “extern” keyword, followed by the variable’s data type and name. This tells the compiler that the variable is declared in another file and should be linked with its definition at link-time.

    Extern variables are commonly used in large software projects where multiple source files need to access the same global variable. They allow for better code organization and modularity by separating the variable’s definition and declaration into different files.

    We can use an external variable to share a variable among multiple C source files. To declare an external variable, you need to use the extern keyword.

    Syntax:

    extern DataType VariableName;
    

    In myfile.h file, we declare an extern Variable

    extern int x=10;//external variable (also global)
    

    In another file, we need include myfile.h file in our header file section.

    #include "myfile.h"
    #include <stdio.h>
    void printValue()
    {
        printf("Global variable: %d", global_variable);
    }
    

    3.6 Register Variables

    In C programming, register variables are a type of automatic variables that are stored in the CPU registers instead of main memory. They are declared using the register keyword, which suggests the compiler to use a CPU register to store the variable for faster access. However, the register keyword is only a hint to the compiler, and the compiler may ignore it if it cannot allocate a register or if it determines that a register variable would not improve performance. Hence, the use of register variables is generally limited to small-sized variables that are used frequently in the program.

    register DataType VariableName = InitializeValue;
    

    What is the Difference Between Variable Declaration and Variable Definition?

    In C programming, variable declaration and variable definition are two concepts that are often used interchangeably, but they have different meanings.

    Variable declaration is the process of announcing to the compiler the existence of a variable, its type, and name. This is done using the syntax:

    
    DataType VariableName;
    
    

    For example, int count; declares a variable called count of type int. Variable declaration does not allocate memory for the variable, but it tells the compiler that the variable will be used in the program.

    Variable definition, on the other hand, not only declares the variable, but it also reserves memory space for it. This is done by providing an initial value to the variable. The syntax for variable definition is:

    
    DataType VariableName = Value;
    
    

    For example, int count = 0; declares and defines a variable called count of type int with an initial value of 0. Variable definition implicitly declares a variable, but variable declaration does not define it.

    Variable declaration is required before using a variable in a program, while variable definition is optional if the variable is not used. However, if a variable is used without being defined, it will result in a compilation error.

    In summary, the difference between variable declaration and definition is that declaration announces the existence of a variable, while definition reserves memory space for it and initializes its value.

    Related Posts

    Leave a Reply