-
Notifications
You must be signed in to change notification settings - Fork 0
C Variables
Creating a variable in C is quite simple, with the easiest variable to create being an integer, so let's start with integers!
The first type of variable, and the easiest type of variable, is an integer or int variable, which is a number without any decimals.
(2 is a valid integer but 2.1 is not)
To define an int variable, use
int my_int = 1; /*Replace 1 with the number you want, of course!*/Floats are referenced in a printf using %d (ex. printf("My int is %d", my_int);)
Most modern (64-bit) computers can handle numbers from –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, which is pretty big, but you should be aware of this!
The second type of variable we will learn about are float ('float') variables, which is a number that can contain decimals (float my_float = 2.1 is valid)
Floats are referenced in a printf using %f (ex. printf("My float is %f", my_float);)
You might see some extra 0s at the end while printing a float, but don't worry about that for now!
The last type of variable we will learn about today is a char variable, which is also known as a string!
Char variables can store text (strings)
The easiest way to define a variable is char * my_char = "text goes here";
Doing this will create a variable named my_char with the string "text goes here"
Strings are referenced in a printf using %s (ex. printf("My char is %s", my_char);)
Char variables can also store ints and floats, but you will need to reference them as prints as what they are (%d or %f, not %c or %s) or you will get nothing.
Example:
#include <stdio.h>
int main(void) {
char my_float = 5.1;
printf("My float is %f", my_float);
}#include <stdio.h>
int main(void) {
float my_float = 5.22;
int my_int = 2;
char * my_char = "Hello World!";
printf("My float is %f\n", my_float);
printf("My int is %d\n", my_int);
printf("My char is %s\n", my_char);
}Output:
My float is 5.220000
My int is 2
My char is Hello World!
Changing a variable's value is easy!
my_char = "new value";
my_int = 9;
my_float = 1.2;
All content on Azetrico Developers is licensed under a Creative Commons Attribution 4.0 International License unless stated otherwise.
