LERAN C PROGRAMMING

Learn one of the most powerful programming languages in the world and become a rockstar developer.

Variables and Constants

In this tutorial, you will learn about variables and rules for naming a variable. You will also learn about different literals in C programming and how to create constants.

Variables

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 on them.

Datatype of Variable

variable in C language must be given a type, which defines what type of data the variable will hold.

It can be:

  • char: Can hold/store a character in it.
  • int: Used to hold an integer.
  • float: Used to hold a float value.
  • double: Used to hold a double value.
  • void

Rules for naming a variable

  • A variable name can have only letters (both uppercase and lowercase letters), digits and underscore.
  • The first letter of a variable should be either a letter or an underscore.
  • There is no rule on how long a variable name (identifier) can be. However, you may run into problems in some compilers if the variable name is longer than 31 characters.

Constants

If you want to define a variable whose value cannot be changed, you can use the #define preprocessor directive or const keyword . They will create a constant. For example,

#include <stdio.h>

/* definig constant using #define */
#define val 10  
#define floatVal 4.5  
#define charVal 'G'  
  
int main() 
{
    /* definig constant using constant keyword */
    // int constant 
    const int intVal = 10;  
  
    // Real constant 
    const float floatVal = 4.14; 
   
    // char constant  
    const char charVal = 'A';  
  
    // string constant 
    const char stringVal[10] = "ABC";  
    
    // YOUR CODE
      
    return 0; 
} 

Here, PI is a symbolic constant; its value cannot be changed.



Previous Next
x
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Privacy Policy That's Fine