C Variable

A C variable is a named storage location in memory that holds a value of a specific data type (such as integer, float, or character). You can use variables to store and manipulate data in your C programs.

About C Variable

Declaration: A variable in C must be declared before it is used. The declaration includes the variable’s name and its data type.


int age

Initialization: A variable can be initialized with a value when it is declared, or its value can be set later in the program.


int age = 35;

Example:


#include <stdio.h>

int main() {
    int age = 35;
    printf("John age is %d", age);
    return 0;  // Exit the program successfully
}

Note: %d is used to print integers value.

Output:

John age is 35

Scope of Variable

A variable’s scope refers to where it can be accessed. A variable can be local (inside a function) or global (outside any function).

Local Variables: These are variables declared inside a function or block. Their scope is limited to that function or block.

Global Variables: These are variables declared outside of any function. They can be accessed by any function in the program.

Example:


#include <stdio.h>

int globalVar = 45;
int main() {
    int localVar = 35;
    printf("local variable %d\n", localVar);
    printf("global variable %d", globalVar);
    return 0;  // Exit the program successfully
}

Output:

local variable 35
global variable 45

Variable Naming Rules

A variable name in C must start with a letter or an underscore and can be followed by letters, digits, or underscores. It is case-sensitive, so age and Age would be different variables.

C Variable – Interview Questions

Q 1: What is a variable in C?

Ans: A variable is a named memory location used to store data.

Q 2: How do you declare a variable in C?

Ans: By specifying data type followed by variable name, e.g., int a;.

Q 3: What are the rules for naming variables in C?

Ans: Must start with a letter or underscore, no spaces, and not a keyword.

Q 4: Can a variable name start with a number?

Ans: No, variable names cannot start with a number.

Q 5: What is variable initialization?

Ans: Assigning an initial value to a variable at the time of declaration.

C Variable – Objective Questions (MCQs)

Q1. Which of the following is the correct way to declare a variable in C?






Q2. Which keyword is used to define a variable that cannot be changed once assigned?






Q3. What is the default value of an uninitialized local variable in C?






Q4. Which of the following variable names is invalid in C?






Q5. Which of the following statements is true about C variables?






Related C Variable Topics