Skip to content
Related Articles

Related Articles

Improve Article

Constants vs Variables in C language

  • Difficulty Level : Basic
  • Last Updated : 28 Jun, 2019
Geek Week

Constant

As the name suggests the name constants is given to such variables or values in C programming language which cannot be modified once they are defined. They are fixed values in a program. There can be any types of constants like integer, float, octal, hexadecimal, character constants etc. Every constant has some range. The integers that are too big to fit into an int will be taken as a long. Now there are various ranges that differ from unsigned to signed bits. Under the signed bit, the range of an int varies from -128 to +127 and under the unsigned bit, int varies from 0 to 255.

Example:




#include <stdio.h>
  
// Constants
#define val 10
#define floatVal 4.5
#define charVal 'G'
  
// Driver code
int main()
{
    printf("Integer Constant: %d\n", val);
    printf("Floating point Constant: %f\n", floatVal);
    printf("Character Constant: %c\n", charVal);
  
    return 0;
}
Output:



Integer Constant: 10
Floating point Constant: 4.500000
Character Constant: G

Variable

A variable in simple terms is a storage place which has some memory allocated to it. Basically, a variable used to store some form of data. Different types of variables require different amounts of memory and have some specific set of operations which can be applied to them.

Variable Declaration:
A typical variable declaration is of the form:

type variable_name;

or for multiple variables:
type variable1_name, variable2_name, variable3_name;

A variable name can consist of alphabets (both upper and lower case), numbers and the underscore ‘_’ character. However, the name must not start with a number.

Example:




#include <stdio.h>
int main()
{
    // declaration and definition of variable 'a123'
    char a123 = 'a';
  
    // This is also both declaration
    // and definition as 'b' is allocated
    // memory and assigned some garbage value.
    float b;
  
    // multiple declarations and definitions
    int _c, _d45, e;
  
    // Let us print a variable
    printf("%c \n", a123);
  
    return 0;
}
Output:
a

Difference between variable and constant

ConstantsVariable
A value that can not be altered throughout the programA storage location paired with an associated symbolic name which has a value
It is similar to a variable but it cannot be modified by the program once definedA storage area holds data
Can not be changedCan be changed according to the need of the programmer
Value is fixedValue is varying
Take a step-up from those “Hello World” programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.



My Personal Notes arrow_drop_up
Recommended Articles
Page :