Wednesday, January 9, 2013

Constant and Variable Types

In C, a variable must be declared before it can be used. Variables can be declared at the start of any block of code, but most are found at the start of each function. Most local variables are created when the function is called, and are destroyed on return from that function.
A declaration begins with the type, followed by the name of one or more variables. For example,

int high, low, results[20];
Declarations can be spread out, allowing space for





 an explanatory comment. Variables can also be initialised when they are declared, this is done by adding an equals sign and the required value after the declaration.

int high = 250;     /* Maximum Temperature */
int low = -40;      /* Minimum Temperature */
int results[20];    /* Series of temperature readings */
C provides a wide range of types. The most common are

There are also several variants on these types.


All of the integer types plus the char are called the integral types. float and double are called the real types.

Constants

A C constant is usually just the written version of a number. For example 1, 0, 5.73, 12.5e9. We can specify our constants in octal or hexadecimal, or force them to be treated as long integers.
  • Octal constants are written with a leading zero - 015.
  • Hexadecimal constants are written with a leading 0x - 0x1ae.
  • Long constants are written with a trailing L - 890L.
Character constants are usually just the character enclosed in single quotes; 'a', 'b', 'c'. Some characters can't be represented in this way, so we use a 2 character sequence.

In addition, a required bit pattern can be specified using its octal equivalent.
'\044' produces bit pattern 00100100.
Character constants are rarely used, since string constants are more convenient. A string constant is surrounded by double quotes eg "Brian and Dennis". The string is actually stored as an array of characters. The null character '\0' is automatically placed at the end of such a string to act as a string terminator.
A character is a different type to a single character string. This is important

0 comments:

Post a Comment

Powered by Blogger.