C Variables

C Variables: Storing Information

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.


1. Declaring Variables

To declare a variable, you must specify its data type followed by its name (identifier).

Syntax:

type variableName;

Declaration Example

#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; }


2. Initializing Variables

You can assign a value to a variable at the time you declare it. This is called initialization.

Syntax:

type variableName = value;

Initialization Example

#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; }


3. Naming Rules for Variables

When naming variables in C, you must follow these standard rules to ensure your code compiles:

  1. Valid Characters: Names can contain letters (a-z, A-Z), digits (0-9), and underscores (_).
  2. Starting Character: Names must begin with a letter or an underscore. They cannot start with a digit.
  3. Case Sensitivity: Variable names are case-sensitive. myVar and myvar are considered two entirely different variables.
  4. No Whitespace: Names cannot contain spaces or special characters like !, #, %, etc.
  5. Keywords: You cannot use C reserved keywords (like int, return, if, while) as variable names.

Good Naming Conventions

While x and y are valid variable names, it's a professional practice to use descriptive names that indicate the variable's purpose.


Exercise

?

Which of the following is a valid variable name in C?