Menu Close

What is Variables in C Programming ?

Posted in C Programming

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. 

1. Declaring a Variable

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;

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 (1.1) and (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.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.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 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.

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
    Related:   C Programming: Relational Operators

    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.

    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.

    Related:   Data Types in C Program

    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 3.3.1 The Application of statis 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.

    Related:   JavaScript Variables, Datatypes, and Variable Names

    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;
    

     

     

    Leave a Reply