Variables Declaration and Definition in C

Variables Declaration and Definition in C

A Variables Declaration and Definition in C is nothing more than a label for a storage location that can be altered by our applications. Each variable in C has a type that governs the amount and layout of its memory, the range of values that can be stored in that memory, and the set of operations that can be applied to the variable.

A variable’s name can contain letters, digits, and the underscore character. It must commence with a letter or underscore. The distinction between capital and lowercase letters exists because C is case-sensitive.

What is Variable?

A variable in C is a memory location’s name. It is used for data storage. Its value is modifiable and it can be reused multiple times. It is a method for representing memory location through a symbol in order to make it easily identifiable.

The Rules for Defining the Variables

  • A variable may contain letters, numbers, and underscores.
  • Only the alphabet and the underscore are permitted as variable name initials. It cannot be the first digit.
  • The variable name cannot contain any spaces.
  • Any reserved words or keywords, such as int, float, etc., cannot be used in a variable name.

Basic variable types

Type Description
CharFrequently a single octet (one byte). It is a type of integers.
IntThe most natural size for a machine’s integers.
FloatA value with single-precision floating point precision.
DoubleA value with double precision floating point.
VoidRepresents the lack of a given type.
Variable Declaration and Initializa...
Variable Declaration and Initialization in JAVA | Java Programming

In addition to Enumeration, Pointer, Array, Structure, Union, etc., the C programming language permits the definition of a variety of other variable types, which we shall discuss in later chapters. Let us learn simply basic variable types in this chapter.

Different Types of Variables in C

There are numerous varieties of variables in c:

  • Local variable
  • Global variable
  • Static variable
  • Automatic variable
  • External variable

Local Variable

A local variable that is declared inside the function or block.

Local variables are variables that are declared inside a function or block. They can only be utilized by statements within the function or code block. Local variables are not accessible to other functions. The following example demonstrates the use of local variables.

It must be declared at the start of the block.

void main_function(){  
int a=20;   //local variable  
}  

You must initialize the local variable prior to using it.

Example Program for Local Variable in C:

  • Local variables will only have application within the function.
  • These variables are declared inside the function and are not accessible from elsewhere.
  • The variables m and n in the example below have scope exclusively within the main function. To test function, these are not visible.
  • Similarly, the scope of the variables a and b is limited to the test function. The main function cannot see these.
#include<stdio.h>
void test();

int main()
{
   int x = 12, y = 22;
        // x, y are local variables of main function
        /*m and n variables are having scope
        within this main function only.
        These are not visible to test funtion.*/
        /* If you try to access x and y in this function,
        you will get 'x' undeclared and 'y' undeclared error */
   printf("\nvalues : x = %d and y = %d", x, y);
   test();
}

void test()
{
   int q = 60, r = 90;
        // q, r are local variables of test function
        /*q and r variables are having scope
        within this test function only.
        These are not visible to main function.*/
        /* If you try to access m and n in this function,
        you will get 'm' undeclared and 'n' undeclared
        error */
   printf("\nvalues : q = %d and r = %d", q, r);
}

Output of the example code:

values : x = 12 and y = 22
values : q = 60 and r = 90

You can try to run here the example code above:

Global Variable

Global variable referred to as a variable declared outside of a function or block. Any function may alter the global variable’s value. It is accessible by all functions. These variables are not restricted to a single function, hence any function may be used to access and modify global variables.

It must be declared at the block’s beginning.

int value=100;  //global variable  
void main_function1(){  
int a=20;  //local variable  
} 

Example Program for Global Variable in C:

  • Global variables will be used throughout the entire program. Anywhere in the application can access these variables.
  • Outside of the main function, this variable is defined. In order for the main function and all other sub functions to see this variable.
#include<stdio.h>
void test();int q = 100, r = 144;
int x = 90, y = 99;

int main()
{
   printf("All variables are accessed from main function");
   printf("\nvalues: q=%d:r=%d:x=%d:y=%d", q,r,x,y);
   test();
}

void test()
{
   printf("\n\nAll variables are accessed from" \
   " test function");
   printf("\nvalues: q=%d:r=%d:x=%d:y=%d", q,r,x,y);
}

Output of the example code:

All variables are accessed from main function
values: q=100:r=144:x=90:y=99

All variables are accessed from test function
values: q=100:r=144:x=90:y=99

You can try to run here the example code above:

Static Variable

Static variable refers to a variable declared with the static keyword. The one allocated statically, whose lifetime spans the duration of the program’s execution. It is declared with the keyword ‘static’, and its value survives between function calls.

void function1(){  
int a=20;//local variable  
static int b=20;//static variable  
a=a+1;  
b=b+1;  
printf("%d,%d",a,b);  
}  

If this function is called multiple times, the local variable will output the same value for each function call, e.g., 21, 21, 21 etc. However, the static variable will output the incremented value for each function call, such as 21, 22, 23, etc.

Automatic Variable

Automatic variables is specified within a block in C are, by default. Using the auto keyword, we can explicitly specify an automatic variable. An automatic variable in computer programming is a local variable that is automatically allocated and deallocated as the program flow enters and exits the variable’s scope. The scope is the lexical context in which a variable is defined, namely the function or block.

void main(){  
int a=20;//local variable (also automatic)  
auto int b=20;//automatic variable  
}  

External Variable

An external variable in the C programming language is a variable defined outside of any function block. A local (automatic) variable, on the other hand, is a variable defined within a function block.

myfile.h

extern int a=20;//external variable (also global)  

variable_program.c

#include "myfile.h"  
#include <stdio.h>  
void printValue(){  
    printf("external variable: %d", external_variable);  
}  

Variable Definition in C

Variable Definition in C is the location and amount of storage for a variable are specified by its definition to the compiler. A data type is specified in a variable definition, which also includes a list of one or more variables of that type.

type variablefunction_list;

In this case, type must be one of the recognized C data types, such as char, w char, int, float, double, bool, or any user-defined object. variable list may have one or more identifier names that are separated by commas. Here are a few legitimate declarations.

int a, b, c;
char c, ch;
float f, price;
double d;

It tells the compiler to create int variables with the names a, b, and c. The line int a, b, and c; declares and defines the variables a, b, and c.

In their declaration, variables can be initialized (given a starting value). The equal sign is followed by a constant expression in the initializer, as shown below.

type variablefunctions_name = value;

Examples include

extern int d = 20, f = 25; // declaration of d and f.
int d = 20, f = 25; // definition and initializing d and f.
byte q= 45; // definition and initializes q.
char y= 'y'; // the variable y has the value 'y'.

Variables with static storage lifetime are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables is indeterminate for definitions without an initializer.

Variable Declaration in C

A Variable Declaration in C assures the compiler that a variable with the specified type and name exists, allowing the compiler to proceed with compilation without requesting detailed information about the variable. A variable’s meaning is only determined at the time of compilation; the compiler requires the real variable definition at the time of linking.

A variable declaration is beneficial when many files are used and the variable is defined in one of the files that will be available at the time of program linking. Use the term extern to declare a variable in any location. A variable can be declared numerous times in a C program, but it can only be defined once per file, function, or block of code.

Example Variable Declaration in C

Consider the following example, in which variables are declared at the top but defined and initialized within the main function.

#include <stdio.h>

// Variable declaration:
extern int w, x;
extern int y;
extern float z;

int main () {

   /* variable definition: */
   int w, x;
   int y;
   float z;
 
   /* actual initialization */
   w = 20;
   x = 40;
  
   y = w + x;
   printf("value of y : %d \n", y);

   z = 70.0/3.0;
   printf("value of z : %f \n", z);
 
   return 0;
}

When the above example code is compiled and executed, the following result is produced:

value of y : 60
value of z : 23.333334

The similar idea applies to function declarations, where you offer a function name at the time of declaration and its actual definition can be provided elsewhere. As an example,

You can try to test here the example above!

// function declaration
int functions();

int main() {

   // function call
   int x = functions();
}

// function definition
int functions() {
   return 0;
}

Lvalues and Rvalues in C

In C, there are two types of expressions.

  • lvalue” expressions are those that make a memory location reference. The left or right side of an assignment can both contain a lvalue. Memory location that identifies an object is referred to as a “l-value”. The left or right side of the assignment operator (=) may contain a l-value. L-value is frequently used as an identification. “Modifiable l-values” are expressions that relate to locations that can be changed. An array type, an incomplete type, or a type with the constant attribute are all prohibited for a changeable l-value. There cannot be any members with the constant attribute in structures or unions for them to have editable lvalues. The value of the variable is the value that is stored at the location designated by the name of the identifier. If an identifier relates to a memory location and its type is arithmetic, structure, union, or pointer, it qualifies as a changeable lvalue. For instance, *ptr is a changeable l-value that identifies the storage region to which ptr points if ptr is a pointer to a storage region. Expressions that locate (designate) things are now referred to as “locator values” in C. One of the following describes the l-value:
    • Any variable’s name, such as an identifier for an integral, floating-point, pointer, structure, or union type.
    • an expression for the subscript ([]) that does not evaluate to an array.
    • an expression with a unary indirection (*) that doesn’t make reference to an array
    • a parenthesized l-value expression.
    • a const thing (a nonmodifiable l-value).
    • indirection through a pointer that, if it’s not a function pointer, produces the desired effect.
    • member access by pointer(-> or.) results in.
  • The term “rvalue” refers to a data value that is kept in memory at a specific address. An rvalue can occur on the right side of an assignment but not the left because it is an expression that cannot have a value assigned to it.

Variables are lvalues, therefore they could show up on the assignment’s left side. Since numerical literals are rvalues, they cannot be assigned and cannot be used in left-side clauses. The following assertions are both true and false.

int x = 68; // valid statement

45 = 67; // invalid statement; would generate compile-time error

Example of Lvalues in C

// declare 'x' an object of type 'int'
int x;

// x is an expression referring to an
// 'int' object as l-value
x = 1;

int y = x; // Ok, as l-value can appear on right

// Switch the operand around '=' operator
9 = x;

// Compilation error:
// as assignment is trying to change the
// value of assignment operator

Example of Rvalues in C

// declare 'x', 'y' an object of type 'int'
int x= 1, y;

x+ 1 = y; // Error, left expression is
		// is not variable(a + 1)

// declare pointer variable 'a', and 'b'
int *a, *b; // *a, *bare lvalue

*a = 1; // valid l-value assignment

// below is invalid - "a + 2" is not an l-value
// a + 2 = 18;

b = a + 5; // valid - "a + 5" is an r-value

// Below is valid - dereferencing pointer
// expression gives an l-value
*(a + 2) = 18;

a = &b;

int arr[20]; // arr[12] is an lvalue; equivalent
			// to *(arr+12)
			// Note: arr itself is also an lvalue

struct S { int m; };

struct S obj; // obj and obj.m are lvalues

// ptr-> is an lvalue; equivalent to (*ptr).m
// Note: ptr and *ptr are also lvalues
struct S* ptr = &obj;

Note: An l-value is necessary for the unary & (address-of) operator. In other words, &n is only a legitimate expression if n is a l-value. Therefore, an expression like &12 is incorrect. Once more, 12 is not addressable because it does not refer to an object.

In the next following post, I’ll create a Constant in C and try to explain its many components in full details. I hope you enjoy this post on Variables in C, in which I attempt to illustrate the language’s core grammar.

Conclusion

This tutorial taught us how to create variables in C, how to give them values, and what happens when a variable is created. While establishing a new variable, we also gained insight into the significance of datatype.

Try to run the C Programming code for free through online

Click the link Below!
C Online Compiler


Leave a Comment