Constants

December 6th, 2009 by Kevin | No Comments | Filed in C Programming

As the name suggests, a constant is a value which will remain fixed over the entire execution of the program.

For example,

int num = 100;              /* here 100 is an integer constant */

char chr = ‘s’;                 /* here ‘s’ is a character constant */

float pi = 3.14;              /* here 3.14 is a floating point constant */

long lng = 123456789L       /*signed long constant indicated by the ‘L’*/

unsigned long ulng = 1234567891UL     /* unsigned long constant indicated by the ‘UL’ */

A character constant is an integer value of the machine’s character set. An example is the ASCII(American Standard Code For Information Interchange) character set. The ASCII code of the character ‘a’ is the integer 97. The entire ASCII chart can be found at http://www.asciitable.com/

Certain character contants are know as escape sequences. They appear to contain two but infact represent just a single character. For instance, ‘\n’ is an escape sequence which represents the newline character which is placed to indicate a newline. Below is a list of several escape sequences.

Escape Sequences

A string constant or a string literal is a collection of character constants ended by an escape sequence ‘\0′. For example, “This is a string” is a string constant. The quotes(“) are used to define the start and end of the strings and are not a part of it. Every string ends with a ‘\0′ escape sequence which is not visible when the string is printed. So the total length of the string constant includes an addition of one more character due to the escape sequence. An empty string “” has a length of 1 due to the escape sequence.

c strings

c strings

It is important to remember the difference between a string and a character. For example, “x” and ‘x’ are completely different as “x” is a string with two characters ‘x’ and ‘\0′ where as ‘x’ is just a single character.

There is also an enumeration constant. An enumeration is a list of integer values.

For example, enum BOOL {NO, YES};

Enumerations always start with 0 and the next constants have successive values unless specified.

For example,
enum YEARS {JAN=1, FEB, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER};

 

Related Posts:

Tags: ,