Friday 23 November 2012

Constants, Variables and Declarations in C

Programming with C Unit 2

Unit 2 Constants, Variables and Declarations
Structure
2.0 Introduction
2.1 Constants
2.1.1 Integer Constants
2.1.2 Real Constants
2.1.3 Character Constants
2.1.4 String Constants
2.1.5 Backslash Character Constants
Self Assessment Questions
2.2 Concept of an Integer and Variable
Self Assessment Questions
2.3 Declaring an Integer Variable
Self Assessment Questions
2.4 The rules for naming Variables
Self Assessment Questions
2.5 Assigning values to variables
2.6 Summary
2.7 Terminal Questions
2.8 Answers to Self Assessment Questions
2.9 Answers to Terminal Questions
2.10 Exercises
2.0 Introduction
The type of a variable determines what kinds of values it may take on. The
type of an object determines the set of values it can have and what
operations can be performed on it. This is a fairly formal, mathematical
definition of what a type is, but it is traditional (and meaningful). There are
several implications to remember:
Programming with C Unit 2
Sikkim Manipal University Page No.: 11
1. The “set of values'' is finite. C's int type can not represent all of the
integers; its float type can not represent all floatingpoint
numbers.
2. When you're using an object (that is, a variable) of some type, you may
have to remember what values it can take on and what operations you
can perform on it. For example, there are several operators which play
with the binary (bitlevel)
representation of integers, but these operators
are not meaningful for and may not be applied to floatingpoint
operands.
3. When declaring a new variable and picking a type for it, you have to
keep in mind the values and operations you'll be needing.
Objectives
At the end of this unit, you will be able to:
· Understand the concept of Constants
· Understand the concept of Integers
· Understand the variable and its declaration in C
2.1 Constants
Constants in C refer to fixed values that do not change during the execution
of a program. C supports several types of constants as illustrated in Fig 2.1.
Constants
Numeric constants Character constants
Integer constants Real constants Single character constants String constants
Fig 2.1
Programming with C Unit 2
Sikkim Manipal University Page No.: 12
2.1.1 Integer constants
An integer constant refers to a sequence of digits. There are three types of
integers, namely decimal, octal and hexadecimal.
Decimal integers consist of a set of digits, 0 through 9, preceded by an
optional – or +.
Examples: 12, 546,
0, 354647, +56
An octal integer constant consists of any combination of digits from the set 0
through 7, with a leading 0.
Examples: 045, 0, 0567
A sequence of digits preceded by 0x or 0X is considered as hexadecimal
integer. They may also include alphabets A through F or a through f. The
letters A through F represent numbers 10 through 15.
Examples: 0X6, 0x5B, 0Xbcd, 0X
The largest integer value that can be stored is machinedependent.
It is
32767 on 16bit
machines and 2,147,483,647 on 32bit
machines. It is also
possible to store larger integer constants on these machines by appending
qualifiers such as U, L and UL to the constants.
Examples: 54637U or 54637u (unsigned integer)
65757564345UL or 65757564345ul (unsigned long integer)
7685784L or 7685784l (long integer)
Program 2.1: Program to represent integer constants on a 16bit
computer
/* Integer numbers on 16bit
machine */
main()
{
printf(“Integer values\n\n”);
printf(“%d %d %d\n”, 32767,32767+1,32767+10);
printf(“\n”);
Programming with C Unit 2
Sikkim Manipal University Page No.: 13
printf(“Long integer values\n\n”);
printf(“%ld %ld %ld\n”, 32767L, 32767L+1L, 32767L+10L);
}
Type and execute the above program and observe the output
2.1.2 Real constants
The numbers containing fractional parts like 67.45 are called real(or floating
point) constants.
Examples: 0.0045, 8.5,
+345.678
A real number may also be expressed in exponential(scientific) notation.
The general form is:
mantissa e exponent
The mantissa is either a real number expressed in decimal notation or an
integer. The exponent is an integer number with an optional plus or minus
sign. The letter e separating the mantissa and the exponent can be written
in either lowercase or uppercase.
Examples: 04e4, 12e2,
1.3E2
7500000000 may be written as 7.5E9 or 75E8.
Floating point constants are normally represented as doubleprecision
quantities. However, the suffixes f or F may be used to force single precision
and l or L to extend doubleprecision
further.
2.1.3 Character constants
A single character constant( or simple character constant) contains a single
character enclosed within a pair of single quote marks.
Examples: ‘6’, ‘X’, ‘;’
Character constants have integer values known as ASCII values. For
example, the statement
printf(“%d”, ‘a’);
Programming with C Unit 2
Sikkim Manipal University Page No.: 14
would print the number 97, the ASCII value of the letter a. Similarly, the
statement
printf(“%c”, 97);
would print the letter a.
2.1.4 String constants
A string constant is a sequence of characters enclosed within double quotes.
The characters may be letters, numbers, special characters and blank
space.
Examples: “Hello!”, “1947”, “5+3”
2.1.5 Backslash character constants
C supports some special backslash character constants that are used in
output functions. A list of such backslash character constants is given in
Table 2.1. Note that each one of them represents one character, although
they consist of two characters. These character combinations are called
escape sequences.
Constant Meaning
‘\b’ back space
‘\f’ form feed
‘\n’ new line
‘\r’ carriage return
‘\t’ horizontal tab
‘\v’ vertical tab
‘\’’ single quote
‘\” ‘ double quote
‘\\’ backslash
‘\0’ null
Table 2.1
Programming with C Unit 2
Sikkim Manipal University Page No.: 15
Self Assessment Questions
i) List different types of constants.
ii) What are the different types of integer constants?
iii) What are escape sequences?
2.2 Concept of an Integer and Variable
Integers are whole numbers with a range of values supported by a particular
machine. Generally, integers occupy one word of storage, and since the
word sizes of machines vary (typically, 16 or 32 bits) the size of an integer
that can be stored depends on the computer. If we use 16 bit word length,
the size of the integer value is limited to the range 32768
to +32767 (that is,
2
15 to +2 15 1
). A signed integer uses one bit for sign and 15 bits for the
magnitude of the number. Similarly, a 32 bit word length can store an
integer ranging from 2,147,483,648
to 2,147,483,647.
In order to provide some control over the range of numbers and storage
space, C has three classes of integer storage, namely short int, int , and
long int, in both signed and unsigned forms. For example, short int
represents fairly small integer values and requires half the amount of
storage as a regular int number uses. A signed integer uses one bit for sign
and 15 bits for the magnitude of the number, therefore, for a 16 bit machine,
the range of unsigned integer numbers will be from 0 to 65,535.
We declare long and unsigned integers to increase the range of values.
The use of qualifier signed on integers is optional because the default
declaration assumes a signed number. The Table 2.2 shows all the allowed
combinations of basic types and qualifiers and their size and range on a 16bit
machine.
Programming with C Unit 2
Sikkim Manipal University Page No.: 16
Type Size (bits) Range
int or signed int
unsigned int
short int or signed short int
unsigned short int
long int or signed long int
unsigned long int
16
16
8
8
32
32
32,768
to 32,767
0 to 65535
128
to 127
0 to 255
2,147,483,648
to 2,147,483,647
0 to 4,294,967,295
Table 2.2
Informally, a variable (also called an object) is a place where you can store
a value so that you can refer to it unambiguously. A variable needs a name.
You can think of the variables in your program as a set of boxes, each with
a label giving its name; you might imagine that storing a value “in'' a variable
consists of writing the value on a slip of paper and placing it in the box.
Self Assessment Questions
State true or false
i) The size of the Integers in C language is same in all the machines.
ii) A ________is a place where we can store values.
iii) Size of int is _________ bits.
2.3 Declaring an Integer Variable
A declaration tells the compiler the name and type of a variable you'll be
using in your program. In its simplest form, a declaration consists of the type,
the name of the variable, and a terminating semicolon:
int i;
The above statement declares an integer variable i.
long int i1, i2;
We can also declare several variables of the same type in one declaration,
separating them with commas as shown above.
Programming with C Unit 2
Sikkim Manipal University Page No.: 17
The placement of declarations is significant. You can't place them just
anywhere (i.e. they cannot be interspersed with the other statements in your
program). They must either be placed at the beginning of a function, or at
the beginning of a braceenclosed
block of statements, or outside of any
function. Furthermore, the placement of a declaration, as well as its storage
class, controls several things about its visibility and lifetime, as we'll see
later.
You may wonder why variables must be declared before use. There are two
reasons:
1. It makes things somewhat easier on the compiler; it knows right away
what kind of storage to allocate and what code to emit to store and
manipulate each variable; it doesn't have to try to intuit the programmer's
intentions.
2. It forces a bit of useful discipline on the programmer: you cannot
introduce variables wherever you wish ; you must think about them
enough to pick appropriate types for them. (The compiler's error
messages to you, telling you that you apparently forgot to declare a
variable, are as often helpful as they are a nuisance: they're helpful
when they tell you that you misspelled a variable, or forgot to think about
exactly how you were going to use it.)
Most of the time, it is recommended to write one declaration per line. For
the most part, the compiler doesn't care what order declarations are in. You
can order the declarations alphabetically, or in the order that they're used, or
to put related declarations next to each other. Collecting all variables of the
same type together on one line essentially orders declarations by type,
which isn't a very useful order (it's only slightly more useful than random
order).
Programming with C Unit 2
Sikkim Manipal University Page No.: 18
A declaration for a variable can also contain an initial value. This initializer
consists of an equal sign and an expression, which is usually a single
constant:
int i = 1;
int i1 = 10, i2 = 20;
Self Assessment Questions
i) What is meant by declaration?
ii) What is an initializer?
iii) State true or false
A single declaration statement can contain variables of different types
2.4 The rules for naming Variables
Within limits, you can give your variables and functions any names you want.
These names (the formal term is “identifiers'') consist of letters, numbers,
and underscores. For our purposes, names must begin with a letter.
Theoretically, names can be as long as you want, but extremely long ones
get tedious to type after a while, and the compiler is not required to keep
track of extremely long ones perfectly. (What this means is that if you were
to name a variable, say, supercalafragalisticespialidocious, the compiler
might get lazy and pretend that you'd named it supercalafragalisticespialidocio,
such that if you later misspelled it supercalafragalisticespialidociouz,
the compiler wouldn't catch your mistake. Nor
would the compiler necessarily be able to tell the difference if for some
perverse reason you deliberately declared a second variable named
supercalafragalisticespialidociouz.)
The capitalization of names in C is significant: the variable names variable,
Variable, and VARIABLE (as well as silly combinations like variAble) are all
distinct.
Programming with C Unit 2
Sikkim Manipal University Page No.: 19
A final restriction on names is that you may not use keywords (the words
such as int and for which are part of the syntax of the language) as the
names of variables or functions (or as identifiers of any kind).
Self Assessment Questions
i) State true or false.
In C, variable names are case sensitive.
ii) A variable name in C consists of letters, numbers and _________
2.5 Assigning values to variables
The assignment operator = assigns a value to a variable. For example,
x = 1;
sets x to 1, and
a = b;
sets a to whatever b's value is. The expression
i = i + 1;
is, as we've mentioned elsewhere, the standard programming idiom for
increasing a variable's value by 1: this expression takes i's old value, adds 1
to it, and stores it back into i. (C provides several “shortcut'' operators for
modifying variables in this and similar ways, which we'll meet later.)
We've called the = sign the “assignment operator'' and referred to
“assignment expressions'' because, in fact, = is an operator just like + or .
C
does not have “assignment statements''; instead, an assignment like a = b is
an expression and can be used wherever any expression can appear. Since
it's an expression, the assignment a = b has a value, namely, the same
value that's assigned to a. This value can then be used in a larger
expression; for example, we might write
c = a = b;
Which is equivalent to?
c = (a = b);
Programming with C Unit 2
Sikkim Manipal University Page No.: 20
and assigns b’s value to both a and c. (The assignment operator, therefore,
groups from right to left.) Later we'll see other circumstances in which it can
be useful to use the value of an assignment expression.
It's usually a matter of style whether you initialize a variable with an initializer
in its declaration or with an assignment expression near where you first use
it. That is, there's no particular difference between
int a = 10;
and
int a;
/* later... */
a = 10;
2.6 Summary
Integers are whole numbers with a range of values supported by a particular
machine. Generally, integers occupy one word of storage, and since the
word sizes of machines vary (typically, 16 or 32 bits) the size of an integer
that can be stored depends on the computer. A variable (also called an
object) is a place where you can store a value. A declaration tells the
compiler the name and type of a variable you'll be using in your program.
The assignment operator = assigns a value to a variable.
2.7 Terminal Questions
1. Distinguish between signed and unsigned integers.
2. What are the components of declaration statement?
3. State the rules for naming a variable in C.
4. What is the use of an assignment operator ?
5. The ____________ of a variable determines what kinds of values it may
take on.
Programming with C Unit 2
Sikkim Manipal University Page No.: 21
6. Find errors, if any, in the following declaration statements.
Int x;
short int x;
long int m; count;
a,b,c: INTEGER;
7. Which of the following are invalid variable names and why?
First.name 2nd_row Maximum
int integer Row total
2.8 Answers to Self Assessment Questions
2.1 i) Integer constants, Real constants, Character constants, String
constants.
ii) Decimal, Octal and Hexadecimal
iii) Backslash character constants are called escape sequences
2.2 i) False
ii) Variable
iii) 16
2.3 i) A declaration tells the compiler the name and type of a variable
you'll be using in your program.
ii) An initializer is used to assign a value to a variable. The initializer
consists of an equal sign and an expression, which is usually a
single constant.
iii) False
2.4 i) True
ii) Underscores
Programming with C Unit 2
Sikkim Manipal University Page No.: 22
2.9 Answers to Terminal Questions
1. A signed integer uses one bit for sign and remaining bits for the
magnitude of the number, whereas an unsigned integer uses all the bits
to represent magnitude.
2. A declaration consists of the type, the name of the variable, and a
terminating semicolon.
3. Variables (the formal term is “identifiers'') consist of letters, numbers,
and underscores. The capitalization of names in C is significant. you
may not use keywords (the words such as int and for which are part of
the syntax of the language) as the names of variables or functions (or as
identifiers of any kind).
4. The assignment operator (=) assigns a value to a variable.
5. type
6. (i) In the first line capital I for Int is not allowed
(ii) In the third line there must be coma between m and count.
(iii) The declaration of integer elements a,b,c is as follows:
int a,b,c;
7. The following are invalid variable names:
(i) First.namebecause
the symbol . is not allowed.
(ii) 2nd_row – because the variable names should not begin with
numbers
(iii) int – because int is a keyword
(iv) Row total – because space is not allowed
Programming with C Unit 2
Sikkim Manipal University Page No.: 23
2.10 Exercises
1. Determine the valid identifiers from below
a) record 1 b) file_2 c) a+b d) return
2. Which of the following are invalid constants and why?
a) 0.001 b) 5x1.5 c) 999999 d) ‘12’
3. Determine which of the following are valid string constants
a) 9:00 p.m b) “Name: c) “chapter 3 (cont\’d)’ d) p,q
4. Explain different types of constants.
5. What are the rules used in naming a variable? Give examples.

No comments:

Post a Comment