C Variables: Understanding Data Storage in C
Discover the concept of variables in C, which serve as containers for storing various data values like numbers and characters. Learn about different types of variables defined with specific keywords, along with examples to illustrate their use.
C Variables
Variables are containers for storing data values, such as numbers and characters.
In C, there are different types of variables (defined with different keywords). Here are some examples:
int
- stores integers (whole numbers), without decimals, such as456
or-456
float
- stores floating-point numbers, with decimals, such as34.56
or-34.56
char
- stores single characters, such as'x'
or'Z'
. Characters are surrounded by single quotes.
Declaring (Creating) Variables
To create a variable, specify its type and assign it a value:
Syntax
type variableName = value;
Where type
is one of the C types (such as int
), and variableName
is the name of the variable (such as y
or studentName
). The equal sign is used to assign a value to the variable.
So, to create a variable that stores a number, consider the following example:
Example
// Create a variable called myNum of type int and assign the value 30 to it
int myNum = 30;
You can also declare a variable without assigning a value and assign the value later:
Example
// Declare a variable
int myNum;
// Assign a value to the variable
myNum = 30;
Output Variables
You learned from the output chapter that you can output values/print text with the printf()
function:
Example
printf("Hello World!");
In many other programming languages (like Python, Java, and C++), you would normally use a print function to display the value of a variable. However, this is not possible in C:
Example
// This will not work as expected
int myNum = 30;
printf(myNum); // Nothing happens