This blog is under construction

Friday, 27 December 2013

Constants in C language

What are constants in c language?
Any value that cannot be changed during the execution of the program is a constant.  And the constant can be numeric or character.  Below are various types of constants.
1. Integer constants
2. Real-number constants
3. Character constants
4. String constants

What are integer constants?
Integer constants are signed or unsigned integers.
-100, 0, 100

If 0x precedes numeric value, then the constant is hexa decimal.
0x1f, 0x2c, 0x1000

If 0 precedes numeric value, then the constant is  octal.
055, 077, 022

If the digits of a value is from any numbers from 0-9, then the constant is decimal
10, 299, 345

What is Real-number constant?
Any signed or unsigned real number(fraction) is called floating point or real-number constant.  And the real constant can be written either in decimal format or exponential format.

Below is the example for decimal format of real number constant.
10.04, 0.34, -4.9267

Below is the example for exponential form of real number constant.
10e2 is equivalent to 10 * 10^2   => 1000
6e-2 is equi alent to 6 * (1/100) => 0.06

What is character constant?
Any character within single quote can be called as character constant.  The default data type of character constant is integer.  Below are few examples of character constants.

'a', 'B', '1', ')', '+', '-' etc

Few characters in C cannot be represented as single character.  For those case, we will use backslash at the front of the character as shown below.
\' - single quote
\" - double quote
\n - new line
\? - question mark
\b - backspace etc.

What are string constants?
A sequence of characters(can be any combination of alpha, numeric or symbols) enclosed within double quotes is called string constant.

"India is my country"
"Delhi - 100 027"
"Hai hello \
how are you"

printf("Hai hello \
how are you");  is equivalent to printf("Hai hello how are you");
Here, backslash helps us to break the string into pieces and write it in multiple lines.

#include <stdio.h>
int main() {
        /* integer constants */
        int signed_int = -100, hexa = 0x100, octal = 011;
        /* real number constants */
        float real1 = 10.4, real2 = 10e-2;
        /* character and string costant */
        char ch = 'a', str[] = "hello \
        /* printing integer, real number, character and string constants */
        printf("Integer constants:\n");
        printf("%d %x %o\n", signed_int, hexa, octal);
        printf("Real number constants:\n");
        printf("%f %f\n", real1, real2);
        printf("Character or String Constants:\n");
        printf("%c  \"%s\"\n", ch, str);
        return 0;

  jp@jp-VirtualBox:~/cpgms/posts$ ./a.out
  Integer constants:
  -100 100 11
  Real number constants:
  10.400000 0.100000
  Character or String Constants:
  a  "hello world"

No comments:

Post a Comment