Constants and Variables in C

Here we will talk out how to define constants and variables in C and also understand their usage.

Constants in C

Any unchanged value in a program during the execution cycle of the program whose value doesn’t change is called constant. There are two types of Constants:

  • Numeric constants – Numeric constants can either be an integer constant or float constants. An integer constant is a signed or unsigned number like -11, 25, -1. A float constant is like -18.54, 2.54, 0.1.
  • Character (string) constants – It can be either a single character constant or a string of characters constant. A single character constant example is ‘c’, ‘k’. A multiple character string example is “Hello World”. ‘\n’ is used to specify line break statements. ‘\t’ specifies a tab space between any two character or string.

You can define a constant in two ways:

  • using define keyword – define is used outside the function block. e.g. #define K 2
  • using const keyword – Const is used within the function block. e.g. const int k =2;

Variables in C

Declaring a variable in C means that you have asked memory for a piece of space to be used for storing some data in future. There are two types of variable:

  • Numeric – Numeric values can either be integer (e.g. 1, 2, -5) or float (e.g. 2.5, 4.7, -1.8).
  • Character – A character can be any alphabet from A to Z or ascii value of 0 to 9.

A variable definition nomenclature is <variable type> <variable name> = <variable initialization>;

e.g. int k = 2; or int k;

Variable initialization is not mandatory. A value can be assigned anywhere later during the program code.

e.g. char k = ‘c’;

or

char k;

k = ‘c’;

We will learn more usage of constants and variables in corresponding chapters.

 

Leave a Reply

Your email address will not be published. Required fields are marked *