Categories: C

Variables & Constants in C

Variables & Constants in C are formed by combining alphabets, numbers, and special symbols. Let us see what are ‘constants’ and ‘variables’ in C.

Variables:
  • An entity that may change during program execution is known as a variable.
  • Variables are the names assigned to the memory locations.
  • These locations can contain integer, real, or character constants.
  • The rules for creating variables are the same as that of identifiers.
  • Variable declaration is a must at the start of the program.

The syntax for declaring a variable:

dataType variable_name;

Example:

int age;
float sum;

Here, age and sum are variables whereas, int and float are data types in C.

Constant:
  • A constant is an entity that doesn’t change during program execution.
  • Constant is also called literal.
  • There are different types of constants in C programming.
ConstantsExamples
Integer constants426,+78,-2900
Real or Floating-point constants+34.09,-98.345,88.456
Character constant‘a’, ‘5’, ‘=’, ‘*’
Octal Constant021, 033, 046
String Constant
“c”, “c program”, “c in javatpoint”
Hexadecimal Constant
0x2a, 0x7b, 0xaa

There are two ways to define constant in C programming.

  1. const keyword
  2. #define preprocessor

const keyword:

#include<stdio.h>    
int main(){    
    const float PI=3.14;    
    printf("The value of PI is: %f",PI);    
    return 0;  
}     

output:

The value of PI is: 3.14

here,

const float PI=3.14

as a result, the value of variable PI is set to 3.14 which cannot be changed during program execution.

#define preprocessor: The #define preprocessor is used to define constant. We will know more about the #define preprocessor directive later on.

#include<stdio.h>
#define PI 3.14
int main(){    
float area=PI*5*5;   
printf("The Area of circle is: %f",area);    
    return 0;  
}     

output:

The Area of circle is: 78.5

note: also read about Identifiers in C & Keywords in C.

next: Data Types in C

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago

Binary Search Tree (BST)

A Binary Search Tree (BST) is a type of binary tree that satisfies the following…

1 year ago