A variable is a name given to a memory location inside our computer where we can store data.
Variable declaration
int age;
In C programming, a variable declaration is a statement that informs the compiler about the name and type of a variable without allocating any memory for it. It essentially tells the compiler that a variable with a specific name and data type will be used in the program. Variable declarations are necessary before you can use a variable in your program.
Variable Initialisation
age = 22
Variable initialisation in C refers to the process of assigning an initial value to a variable when it is declared.
We can write variable declaration and initialisation in single line: int age = 22;
Changing values in variable
#include <stdio.h>
int main(){
int age = 25;
printf("Age: %d", age);
age = 31;
printf("\nNew AGE: %d", age);
return 0;
}
%d
is format specifier. It is a special character sequence used in the printf and scanf functions (and related functions) to specify the type and format of the data that will be input or output.\n
is used for new line.
Assigning one variable to another variable
#include <stdio.h>
int main(){
int firstNumber = 33;
printf("firstNumber = %d", firstNumber);
int secondNumber = firstNumber;
printf("\nsecondNumber = %d", secondNumber);
return 0;
}
Declaring two variable in a single line
#include <stdio.h>
int main(){
int variable1, variable2=25;
return 0;
}
Variable naming convention
- Use camel case variable like
myAge
,firstName
,lightSpeed
. Cannot:- Create variable names with space in between.
int first number
- Start variable names with numbers.
int 1number
- Use keywords as variables.
int if
- Create variable names with space in between.
Top comments (4)
Dennis Ritchie (the creator of C) disagrees with the use of CamelCase. It is not the common naming convention in C.
You neglected to mention that:
_
counts as a letter._
are reserved for use by the implementation._
followed by either a capital letter or_
are also reserved for use by the implementation.The full list is here.
Your example of declaring two variables in the same line makes it seem like both are initialized to 25 when that is not true.
Thanks for your valuable comment. But what is the problem with declaring two variables in a single line. I have done that in many occasions for declaring and initialising same type of values.
Strictly speaking, nothing. But if you read what I actually said, your example:
looks to someone not familiar with C like that might assign
25
tovariable2
and also tovariable1
when in realityvariable1
is uninitialized.Yeah okay.