In C programming, a variable is a named storage location in the computer's memory used to hold data. Think of a variable as a container that holds a value, which can be changed (vary) during the execution of a program.
Before you can use a variable in C, you must declare it. Declaring a variable tells the compiler what type of data it will hold and what its name is.
To declare a variable, you must specify its data type followed by its name (identifier).
Syntax:
type variableName;
type: Specifies the kind of data the variable will store (e.g., int for integers, float for floating-point numbers, char for characters).variableName: The unique name you give to the variable.#include <stdio.h>int main() { int age; // Declares an integer variable named 'age' float salary; // Declares a float variable named 'salary' char grade; // Declares a character variable named 'grade'
return 0; }
You can assign a value to a variable at the time you declare it. This is called initialization.
Syntax:
type variableName = value;
#include <stdio.h>int main() { int myNum = 15; // Integer (whole number) float myFloatNum = 5.99; // Floating point number char myLetter = 'D'; // Character
// Printing variables printf("My number is %d\n", myNum); printf("My float is %f\n", myFloatNum); printf("My letter is %c\n", myLetter);
return 0; }
When naming variables in C, you must follow these standard rules to ensure your code compiles:
_).myVar and myvar are considered two entirely different variables.!, #, %, etc.int, return, if, while) as variable names.While x and y are valid variable names, it's a professional practice to use descriptive names that indicate the variable's purpose.
studentAge, totalScore, isGameOvera, b1, tmp_val_2Which of the following is a valid variable name in C?