Variables and constants in C


Variables are the storage location in memory that holds some value. We define a variable to make sure a stored value in memory is accessible by user later. Variables are accessed by their identifiers(Symbolic name that refer to the value stored in the memory) to which they are linked with. In order to use any variable and the value it contains, the variable must be declared first.

Declaring variables in C:

Syntax: data-type variable-name;
Here data-type refers to valid C Data type.
And variable-name refers to valid C identifier.
Note: In C all variables must be declared on the top.
int num1;
The above code in C will declare an integer variable in memory with Garbage value. Garbage value is a random value of specific type(int in our case) stored in the variable. Hence, variables in C must be initialized prior to their use.

Initializing a variable:

Assigning a value to the variable is called as initializing a variable. Values are initialized or assigned to any variable using assignment operator =.
int num1 = 10;
Above code will now declare an integer variable num1 in memory with 10 stored in it.

Declaring multiple variables:

Multiples variables in C can be declared one after another declaration.
int num1;
int num2 = -30;
unsigned int num3 = 10;
float num4 = 1.2;
char ch = 'a';
The above code will declare an integer variable num1 with garbage value, num2 with value -30, an unsigned integer variable with value 10, float variable num4 with value 1.2 and a character variable ch with value 'a'.
Note: Values of character variable must be assigned inside a single quote. And must only contain single character.

Declaring multiple variables of same type:

Multiple variables of same type can be declared and initialized by separating them with comma,.
int num1, num2, num3;
int num4 = 10, num5, num6 = -1290;
The above code will declare 6 integer variables num1, num2, num3, num5 uninitialized containing garbage values and num4 with value 10, num6 with value -1290.

View next C tutorial How to take simple input from user.

Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment