Jun 7, 2014

C Programming #05: Constants

In the previous section we learned about variables and in this section we will see about constants.

Constant data  will not  change with respect to time and space. Constant data can be of the following type in C
  1. Characters 
  2. Integers
  3. Floating
  4. String


Characters

In C all character constants are placed in between single quote(' ').For example 'a', 'b', '+'. we can also represent it using the ASCII value. For example ASCII value of 'a' is hex 61, this is represented as '\0x61'. Counter intuitively all character constants takes size of integer.


Integers

While representing integers' ,'(comma) is not used in between. For example  3445 is valid C constant while 3,445 is invalid. Integer constant takes size of  integer value.


Float

Float constants are stored as double.(Float constant takes the size of double). If you want explicitly a floating constant then 'f' is used as suffix to it.

For example: 2.3f


String

String constant are represented between double quotes(" "). For example "This is a constant string".

Size of string constant is number of characters in it +1 (+1 because a NULL character is placed at the end of string to represent end of string).


Program to find sizeof of various constants

#include <stdio.h>

int main()
{
  printf("Size of character constant is  %d\n", sizeof('a'));
  printf("Size of integer constant is    %d\n", sizeof(123));
  printf("Size of float constant is      %d\n", sizeof(1.2));
  printf("Size of float(suf) constant is %d\n", sizeof(1.2f));
  printf("Size of string constant is     %d\n", sizeof("This is constant"));
  return 0;
}
output of the above program is

Size of character constant is  4
Size of integer constant is    4
Size of float constant is      8
Size of float(suf) constant is 8
Size of string constant is     17
Note: In general on 32 bit machine we have following typical size

character - 1 byte
integer   - 4 byte
float     - 4 byte
double    - 8 byte

If two string constants are placed side by side, C compiler concatenates it.


Program to show string concatenation

#include <stdio.h>

int main()
{
    printf("This" "is" "a" "contatenated" "string" "\n");
    return 0;
}
Output of above program is
Thisisacontatenatedstring

Links

Quiz - Not Yet written !!
Next Article -  C Programming #06: Operators - Introduction
Previous Article - C Programming #04: Datatypes and Variable
All Article - C Programming

No comments :

Post a Comment