2 The C Declarations – Programming in C, 3/e, 3rd Edition

CHAPTER 2

The C Declarations

Chapter Outline
2.1  INTRODUCTION

The programming languages are designed to support certain kind of data, such as numbers, characters, strings, etc., to get useful output known as result/information. Data consists of digits, alphabets and symbols.

A program should support these data types for getting the required output known as information. A program is a set of statements, which performs a specific task, executed by users in a sequential form. These statements/instructions are formed using certain words and symbols according to the rules known as syntax rules or grammar of the language. Every program must accurately follow the syntax rules supported by the language.

In this chapter, C character set, the type of variables, types of tokens, delimiters, data types, variable initialization and dynamic initialization are described.

2.2  THE C CHARACTER SET

A character is a part of a word, sentence or paragraph. By using different characters, words, expressions and statements can be created on the basis of the requirement. This creation depends upon the computer on which a program runs.

A character is represented by any alphabets in lowercase or uppercase, digits or special characters.

Figure 2.1 presents valid C character set which are as follows: (i) Letters (ii)Digits (iii) White Spaces & Escape Sequences and (iv) Special Characters. As C character set consists of escape sequences so each escape sequence begins with back slash (\) and it represents a single character. Any character can be represented as character constant using escape sequence.

Figure 2.1  C character set

The complete character set is listed in Tables 2.1 and 2.2.

Table 2.1  Character set

Letters

Digits

White Spaces and Escape Sequences

Uppercase A to Z

All decimal digits 0 to 9

Back space \b

Lowercase a to z

Horizontal tab \t

Vertical tab \v

New line \n

Form feed \f

Backslash \\

Alert bell \a

Carriage return \r

Question mark \?

Single quote \’

Double quote \”

Octal number \o or \oo or \ooo

Hexadecimal number \xhh

The special characters listed in Table 2.2 are represented in the computer by numeric values. The C characters are assigned unique codes. There are many character codes used in the computer system. The widely and standard codes used in computer are ASCII and EBCDIC (Extended Binary Coded Decimal Interchange Code).

Table 2.2  List of special characters

ASCII Code: ASCII stands for American Standard Code for Information Interchange, is the code of two types. One uses 7 bits and other uses 8 bits. The 7-bit code represents 128 different characters and the 8-bit code represents 256 characters. For example, the character A is represented in 7-bit code as 10000012(decimal 65). Refer to Appendix A for the list of characters and their equivalent number.

2.3  DELIMITERS

The language pattern of C uses special kind of symbols, which are called delimiters. They are depicted in Table 2.3.

Table 2.3  Delimiters

Delimiters

Symbols

Uses

Colon

:

Useful for label

Semi-colon

;

Terminates statements

Parenthesis

()

Used in expression and function

Square brackets

[]

Used for array declaration

Curly braces

{}

Scope of statement

Hash

#

Preprocessor directive

Comma

,

Variable separator

Angle brackets

<>

Header file

2.4  TYPES OF TOKENS

A compiler designer prescribes rules for making a program using statements. The smallest unit in a program/statement is called a token. The compiler identifies them as tokens. Tokens are classified in the following types. Figure 2.2 shows the types of tokens supported by C.

Figure 2.2  Types of tokens

The tokens are as follows:

  1. Keywords: Key words are reserved by the compiler. There are 32 keywords (ANSI Standard).
  2. Variables: These are user defined. Any number of variables can be defined.
  3. Constants: Constants are assigned to variables.
  4. Operators: Operators are of different types and are used in expressions.
  5. Special Characters: These characters are used in different declarations in C.
  6. Strings: A sequence of characters.
2.5  THE C KEYWORDS

The C keywords are reserved words by the compiler. All the C keywords have been assigned fixed meanings and they cannot be used as variable names. However, few C compilers allow constructing variable names, which exactly coincide with the keywords. It is suggested that the keywords should not be mixed up with variable names. For utilizing the keywords in a program, no header file is required to be included. The descriptions of the keywords are explained in the different programs/ chapters. The 32 C keywords provided in ANSI C are listed in Table 2.4.

Table 2.4  C keywords

2.6  IDENTIFIERS

A symbolic name is used to refer to a variable, constant, function, structure, union etc. This process is done with identifiers. In other words, identifiers are the names of variables, functions, arrays, etc. They refer to a variety of entities such as structures, unions, enumerations, constants, typedef names, functions and objects (see Figure 2.3). An identifier always starts with an alphabet, and it is a plain sequence of alphabets and/or digits. C identifier does not allow blank spaces, punctuations and signs.

Figure 2.3  Identifiers

Identifiers are user-defined names. They are generally defined in lowercase letters. However, the uppercase letters are also permitted. The underscore (_) symbol can be used as an identifier. In general, an underscore is used by a programmer as a link between two words for the long identifiers.

The programmer can refer to programming example 2.3 in which the identifiers are not defined in lowercase but with a combination of lowercase and uppercase letters.

Valid identifiers are as follows:

length, area, volume, sUM, Average

Invalid identifiers are as follows:

Length of line, S+um, year’s

Example:

User-defined identifiers are as follows:

  1. #define N 10
  2. #define a 15

Here, ‘N’ and ‘a’ are user-defined identifiers.

2.7  CONSTANTS

The constants in C are applicable to the values, which do not change during the execution of a program. There are several types of constants in C. They are classified into following groups as given in Figure 2.4 (e.g. Table 2.5).

Figure 2.4  C constants

Table 2.5  Constant types

Example

Constant Type

542

Integer constant

35.254

Floating-point constant

0 × 54

Hexadecimal integer constant

171

Octal integer constant

‘C’

Character constant

“cpp”

String constant

2.7.1  Numerical Constants

  1. Integer Constants: These constants are represented with whole numbers. They require a minimum of 2 bytes and a maximum of 4 bytes of memory.

    The following concepts are essential to follow the numerical constants:

    1. Numerical constants are represented with numbers. At least one digit is needed for representing the number.
    2. The decimal point, fractional part, or symbols are not permitted. Neither blank spaces nor commas are permitted.
    3. Integer constant could be either positive or negative or may be zero.
    4. A number without a sign is assumed as positive.

    Some valid examples: 10, 20, +30, –15, etc.

    Some invalid integer constants: 2.3, .235, $76, 3*^6, etc.

    Besides representing the integers in decimal, they can also be represented in octal or hexadecimal number system based on the requirement.

    Octal number system has base 8 and the hexadecimal number system has base 16. The octal numbers are 0, 1, 2, 3, 4, 5, 6, and 7 and the hexadecimal numbers are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F.

    The representation of octal numbers in C would be done with leading digit 0 and for hex representation, with leading OX or OX.

    Examples of octal and hexadecimal numbers:

    Octal numbers – 027, 037, 072

    Hexadecimal numbers – 0X9, 0Xab, 0X4

  2. Real Constants: Real constants are often known as floating point constants. Real constants can be represented in exponential or fractional form. Integer constants are unfit to represent many quantities. Many parameters or quantities are defined not only in integers but also in real numbers. For example, length, height, price, distance, etc. are also measured in real numbers.

    The following concepts are essential to follow the real numbers:

    1. The decimal point is permitted.
    2. Neither blank spaces nor commas are permitted.
    3. Real numbers could be either positive or negative.
    4. The number without a sign is assumed as positive.

    Examples of real numbers are 2.5, 5.521, 3.14, etc.

    The real constants can be written in exponential notation, which contains fractional and exponential parts. For example, the value 2456.123 can be written as 2.4561 X e+3.

    The part that precedes e is called mantissa and the part that follows it is an exponent. In this example, 2.4561 is the mantissa and +3 is the exponent.

    The following points must be noted while constructing a real number in exponential form:

    1. The real number should contain a mantissa and an exponent.
    2. The letter ‘e’ separates the mantissa and the exponent and it can be written in lower or upper case.
    3. The mantissa should be either a real number represented in decimal or integer form.
    4. The mantissa may be either positive or negative.
    5. The exponent should be an integer that may be positive or negative.

    Some valid examples are 5.2e2,–2, 5.0e–5, 0.5e–3, etc.

    In double type also the real numbers can be expressed with mantissa and exponent parts.

2.7.2  Character Constant

  1. Single Character Constants: A character constant is a single character. It can also be represented with single digit or a single special symbol or white space enclosed within a pair of single quote marks or character constants are enclosed within single quotation marks.

    Example:

    ‘a’, ‘8’, ‘−’

    Length of a character, at the most, is one character.

    Character constants have integer values known as ASCII values. For example the statement printf (“%c %d”, 65, ‘B’) will display character ‘A’ and 66.

  2. String Constants: String constants are a sequence of characters enclosed within double quote marks. The string may be a combination of all kinds of symbols.

    Example:

    “Hello”, “India”, “444”, “a”.

    A programming example is given for various constants.

2.1  Write a program on various constants.

void main()

{

int x;

float y;

char z;

double p;

clrscr();

x=20;

y=2e1;

z=‘a’;

p=3.2e20;

printf(“\n%d %10.2f %c %.2lf”,x,y,z,p);

getche();

}

OUTPUT:

20   20.00   a   320000000000000000000.00

2.8  VARIABLES

Variables are the basic objects manipulated in a program. Declaration gives an introduction of variable to compiler and its properties like scope, range of values and memory required for storage. A variable is used to store values. It has memory location and can store single value at a time.

When a program is executed, many operations are carried out on the data. The data types are integers, real or character constants. The data is stored in the memory, and at the time of execution it is fetched for carrying out different operations on it.

A variable is a data name used for storing a data value. Its value may be changed during the program execution. The variable value keeps on changing during the execution of the program. In other words, a variable can be assigned different values at different times during the program execution. A variable name may be declared based on the meaning of the operation. Variable names are made up of letters and digits. Some meaningful variable names are as follows.

Example:

height, average, sum, avg12

2.2  Write a program to declare and initialize variables and display them.

void main()

{

int age=20;

float height=5.4;

char sex=‘M’;

clrscr();

printf(“Age :%d \nHeight : %g \nSex : %c”,age,height,sex);

}

OUTPUT:

Age: 20

Height: 5.4

Sex: M

Explanation:

In the above program, int, height and char variables are declared and values are assigned. Using printf() statement values are displayed.

2.9  RULES FOR DEFINING VARIABLES
  1. A variable must begin with a character or an underscore without spaces. The underscore is treated as one type of character. It is very useful to increase readability of variables having long names. It is advised that the variable names should not start with underscore because library routines mostly use such variable names.
  2. The length of the variable varies from compiler to compiler. Generally, most of the compilers support eight characters excluding extension. However, the ANSI standard recognizes the maximum length of a variable up to 31 characters. Names of functions and external variables length may be less than 31 because external names may be used by assemblers and loaders over which language has no control. For external names, the variable names should be of six characters and in single case.
  3. The variable should not be a C keyword.
  4. The variable names may be a combination of uppercase and lowercase characters. For example, suM and sum are not the same. The traditional practice is to use lowercase characters for variable names and uppercase letters for symbolic constants.
  5. The variable name should not start with a digit.
  6. Blanks and commas are not permitted within a variable name.

2.3  Write a program to declare variables with different names and data types.

void main()

{

int Num=12;

int WEIGHT = 25;

float HeIgHt=4.5;

char name[10]=“AMIT”;

clrscr();

printf(“Num :%d \nWEIGHT : %d \nHeight : %g \nName =%s”,Num,WEIGHT,HeIgHt,name);

}

OUTPUT:

Num: 12

WEIGHT: 25

Height: 4.5

Name = AMIT

Explanation:

In this program, you might have noticed that variables of different data types with different naming styles are defined. For example Num, WEIGHT, HeIgHt and name are variables. Values are assigned to variables and displayed in the same way as usual.

2.10  DATA TYPES

All C compilers support a variety of data types. This enables the programmer to select the appropriate data type as per the need of the application. Generally, data is represented using numbers or characters. The numbers may be integers or real. The basic data types are char, int, float and double.

The C supports a number of qualifiers that can be applied to these basic data type. The short and long qualifiers provide different length to int. The short is always 16 bits and long is 32 bits, i.e. int is either 16 or 32 bits. The compiler is free to choose a suitable size depending upon the hardware. However, the restriction is that short or int is at least of 2 bytes and long is at least of 4 bytes. The short should not be longer than int and int should not be longer than long.

The unsigned and signed qualifiers can be applied to char, int and long. The unsigned data types are always zero or positive. They follow the law of arithmetic modulo 2n, where n is the number of bits in the type. For example, char are 8 bits with combination of negative and positive values (−128 to 127) (two’s complement). The unsigned char supports values 0 to 255. The characters are signed or unsigned, the printable char are always positive (see Figure 2.5 for a detailed classification).

Figure 2.5  C data types

C data type can be classified as follows:

  1. Basic Data Type:

    (a) Integer (int), (b) character (char), (c) floating point (float), (d) double floating point (double).

  2. Derived Data Type: Derived data types are pointers, functions and arrays. Pointers are explained in Chapter 9, functions are explained in Chapter 10 and arrays are explained in Chapter 7.
  3. User-defined Type: Struct, union and typedef are user-defined data types, which are explained in Chapter 13.
  4. void Data Type: This data type is explained in Chapter 10.
2.11  C DATA TYPES
  1. Integer Data Type
    1. int, short and long

      All C compilers offer different integer data types. They are short and long. Short integer requires half the space in memory than the long. The short integer requires 2 bytes and long integers 4 bytes. Brief description on them is given in Table 2.6.

      Table 2.6  Difference between short and long integers

      Short Integer

      Long Integer

      Occupies 2 bytes in memory

      Occupies 4 bytes in memory

      Range: −32,768 to 32,767

      Range: −2147483648 to 2147483647

      Program runs faster

      Program runs slower

      Format specifier is %d or %i

      Format specifer is %ld

      Example:

      Example:

      int a=2;

      long b=123456;

      short int b=2;

      long int c=1234567;

      When variable is declared without short or long keyword, the default is short-signed int.

    2. Integers Signed and Unsigned

      The difference between the signed integers and unsigned is given in Table 2.7.

      Table 2.7  Difference between signed and unsigned integers

      Signed Integer

      Unsigned Integer

      Occupies 2 bytes in memory

      Occupies 2 bytes in memory

      Range: −32,768 to 32,767

      Range: 0 to 65535

      Format specifier is %d or %i

      Format specifier is %u

      By default signed int is short signed int

      By default unsigned int is short unsigned int

      There are also long signed integers having Range from −2147483648 to 2147483647.

      There are also long unsigned int with range 0 to

      Example:

      4294967295

      int a=2;

      Example:

      long int b=2;

      unsigned long b=567898;

      unsigned short int c=223;

      When a variable is declared as unsigned the negative range of the data type is transferred to positive, i.e. doubles the largest size of the possible value. This is due to declaring unsigned int; the 16th bit is free and not used to store the sign of the number.

  2. char, signed and unsigned: Brief description on these data types is given in Table 2.8

    Table 2.8  Difference between signed and unsigned char

    Signed Character

    Unsigned Character

    Occupies 1 bytes in memory

    Occupies 1 bytes in memory

    Range: −128 to 127

    Range: 0 to 255

    Format specifier: %c

    Format specifier: %c

    When printed using %d format specifier,  prints ASCII character.

    When printed using %d format specifier, prints ASCII character

    char ch=‘b’;

    unsigned char =‘b’;

  3. Floats and Doubles: Table 2.9 shows the description of floats and double floats.

    Table 2.9  Difference between floating and double floating

    Floating

    Double Floating

    Occupies 4 bytes in memory

    Occupies 8 bytes in memory

    Range: 3.4e−38 to +3.4e+38

    Range: 1.7 e−308 to +1.7e+308

    Format string: %f

    Format string: %lf

    Example:

    Example:

    float a;

    double y;

    There also exist long double having ranged 3.4e − 4932 to 1.1e + 4932 and occupies 10 bytes in memory.

    Example:

    long double k;

  4. Entire data types in C: The entire data types supported by the C as illustrated above are given in Table 2.10 for the convenience of the reader for understanding.

    Table 2.10  Data types and their control strings

    *The size may vary according to the number of variables used with enum data type.

2.12  INTEGER AND FLOAT NUMBER REPRESENTATIONS

2.12.1  Integer Representation

Recall that an integer with sign is called a signed integer. The signed integer has signs positive or negative. The signs are represented in the computer in the binary format as 1 for − (minus) and 0 for + (plus) or vice versa. The sign bit is always coded as leftmost bit. At the time of storing the signed number, system reserves the leftmost bit for the representation of the sign of the number.

For example, positive signed numbers are represented in the form called signed magnitude form. In this form, the sign is represented by a binary 0 and the remaining magnitude by equivalent binary form.

+7 is represented as 0 0000111

The signed negative integers can be represented in any one of the following forms:

  1. signed—magnitude form
  2. signed—1’s complement form
  3. signed—2’s complement form

In the signed magnitude form, the sign of the number is represented as 1 and the magnitude by equivalent binary form.

Example:

−7 is represented as 1 0000111

In the signed 1’s complement form, the sign of the integer is indicated by 1 and the magnitude is shown in 1’s complement form as follows,

−7 is represented as 1 1111000

In the above signed − 2’s complement form, the sign is indicated by 1 and magnitude by 2’s complement form as follows,

−7 is represented by 1 1111001

2.12.2  Floating-Point Representation

In most of the applications, fractions are often used. The system of the number representation that keeps track of the position of binary and decimal point is better than the fixed-point representation. This system is called floating-point representation.

The real number is integer part as well as fractional part. The real number is also called floating-point number. These numbers are either positive or negative. The real number 454.45 can be written as 4.5445 × 102 or 0.45445 × 103. This type of representation of number is called the scientific representation. Using this scientific form, any number can be expressed as combination of mantissa and an exponent or we can say the number ‘n’ can be expressed as n=mre where m is the mantissa and r is the radix of the number system and e is the exponent. Mantissa is the fixed-point number. The exponent indicates the position of the binary or decimal point. For example, the number 454.45

0.45445

3

Mantissa

Exponent

The zero in the left most position of the mantissa and exponent indicates the plus sign. The mantissa can be a fraction or integer depending upon make of a computer. Most of the computers use mantissa for fractional system representation.

Example in C:

1.2 E + 12, 2.5E − 2

2.13  DECLARING VARIABLES

The declaration of variables should be done in declaration part of the program. The variable must be declared before they are used in the program. Declaration ensures the following two things: (i) compiler obtains the variable name and (ii) it tells to the compiler data type of the variable being declared and helps in allocating the memory. The variable can also be declared before main() such variables are called external variables. The syntax of declaring a variable is as follows.

Syntax:

Data_type variable_name;

Example:

int age;

char m;

float s;

double k;

int a,b,c;

The int, char, float and double are keywords to represent data types. Commas separate the variables, in case variables are more than one.

Table 2.11 shows various data types and their keywords.

Table 2.11  Data types and keywords

Data Types

Keyword

Character

char

Signed character

signed char

Unsigned character

unsigned char

Integer

int

Signed integer

signed int

Unsigned integer

unsigned int

Unsigned short integer

unsigned short int

Signed long integer

signed long int

Unsigned long integer

unsigned long int

Floating point

float

Double floating point

double

Extended double point

long double

2.14  INITIALIZING VARIABLES

Variables declared can be assigned or initialized using assignment operator ‘=’. The declaration and initialization can also be done in the same line.

Syntax:

variable_name = constant;

or

data_type variable_name= constant;

Example:

x=5; where x is an integer variable.

Example:

int y=4;

Example:

int x,y,z;         /* Declaration of variables */

The third example as cited above for declaration of variables is also a valid statement. Illustration of the initialization of a variable is shown in Figures 2.6 and 2.7.

Figure 2.6  Value assignment

Figure 2.7  Multiple assignment

In Figure 2.7, the variable z is assigned a value 1, and z then assigns its value to y and again y to x. Thus, initialization in chain system is done. However, note that following declarations are invalid:

int x=y=z=3;         /* invalid statement */

2.15  DYNAMIC INITIALIZATION

The initialization of variable at run time is called dynamic initialization. Dynamic refers to the process during execution. In C initialization can be done at any place in the program; however the declaration should be done at the declaration part only. Consider the following program.

2.4  Write a program to demonstrate dynamic initialization.

void main()

{

int r=2;

float area=3.14*r*r;

clrscr();

printf(“Area=%g”,area);

}

OUTPUT:

Area=12.56

Explanation:

In the above program, area is calculated and assigned to variable area. The expression is solved at a run time and assigned to area at a run time. Hence, it is called dynamic initialization.

2.16  TYPE MODIFIERS

The keywords signed, unsigned, short and long are type modifiers. A type modifier changes the meaning of basic data type and produces a new data type. Each of these type modifiers is applicable to the basic data type int. The modifiers signed and unsigned are also applicable to the type char. The long type modifier can be applicable to double type.

Example:

long l;         /* int data type is applied */

int s;         /* signed is default */

unsigned long int;         /* int keyword is optional */

2.5  Write a program to declare different variables with type modifiers and display them.

void main()

{

short t=1;

long k=54111;

unsigned u=10;

signed j=-10;

clrscr();

printf(“\n t=%d”,t);

printf(“\n k=%ld”,k);

printf(“\n u=%u”,u);

printf(“\n j=%d”,j);

}

OUTPUT:

t=1

k=54111

u=10

j=-10

Explanation:

Here in the above program, all the variables are of integer type. The variable t and k are short and long type, whereas u and j are unsigned and signed integers, respectively.

2.17  TYPE CONVERSION

In C, it is possible to convert one data type to another. This process can be done either explicitly or implicitly. The following section describes explicit type conversion.

  1. Explicit type conversion

    a) Sometimes a programmer needs the result in certain data type, for example division of 5 with 2 should return float value. Practically the compiler always returns integer values because both the arguments are of integer data type.

  2. Implicit type conversion

    In C automatically ‘lower’ data type is promoted to ‘upper’ data type. For example, data type char or short is converted to int. This type of conversion is called as automatic unary conversion. Even when binary operator has different data types, ‘lower’ data type is converted to ‘upper’ data type.

    In case an expression contains one of the operands as unsigned operands and another non-unsigned, the latter operand is converted to unsigned.

    Similarly, in case an expression contains one of the operands as float operands and another non-float, the latter operand is converted to float.

    Similarly, in case an expression contains one of the operands as double operand and another non-double, the latter operand is converted to double.

    Similarly, in case an expression contains one of the operands as long int and the other unsigned int operands, the latter operand is converted to long int.

    For the sake of understanding, the following table describes automatic data type conversion from one data type to another while evaluating an expression. a

2.6  The following program explains the above concepts.

#include <stdio.h>

#include <conio.h>

int main()

{

short a=5;

long int b=123456;

float c=234.56;

double d=234567.78695;

clrscr();

 

printf(“%lf”,((a+b)*c)/d);

return 0;

}

OUTPUT:

123.456900

Explanation:

In the above program, we have taken the variable ‘a’ as short int, ‘b’ as long, c as float and ‘d’ as double. The expression ((a + b)*c)/d) gives the result as double float.

Sometimes a programmer needs the result in a certain data type, for example division of 5 with 2 should return float value. Practically, the compiler always returns integer values because both the arguments are of integer data type. This can be followed by the execution of the following program.

2.7  Write a program to change data type of results obtained by division operations.

void main()

{

clrscr();

printf(“\n Division operation Result”);

printf(“\n Two Integers (5 & 2) : %d”,5/2);

printf(“\n One int & one float (5.5 & 2) : %g”,5.5/2);

printf(“\n Two Integers (5 & 2) : %g”,(float)5/2);

}

OUTPUT:

Division operation

Result

Two Integers (5 & 2):

2

One int & one float (5.5 & 2):

2.75

Two Integers (5 & 2):

2.5

Explanation:

In the first division, operation data types are chosen as integer. Hence, the result turns out to be an integer. Actually, the result should be a float value but the compiler returns an integer value. In the second division operation, a float value is divided by an integer. The result of division in this case, yields a float. The limitation of the first operation is removed in the third division operation using type conversion. Here, both the values are of integer type. The result obtained is converted into float. The program uses type casting which is nothing but putting data type in a pair parenthesis before operation. The programmer can specify any data type.

  1. Suppose you assign a float value to an integer variable.

    Example:

    int x=3.5;

    Here, the fraction part will not be assigned to integer variable and the part will be lost. The integer is 2 byes length data type without fractional part and float is 4 bytes data type with fractional part.

  2. In another example, suppose you assign 35425 to int x; you will not get expected result because 35425 is larger than short integer range.

    The following assignments are invalid:

    int=long;

    int=float;

    long=float

    float=double

    The following assignments are valid:

    long=int

    double=float

    int=char

2.18  WRAPPING AROUND

When the value of variable goes beyond its limit, the compiler would not flag any error message. It just wraps around the value of a variable. For example, the range of unsigned integer is 0 to 65535. In this type, negative values and values greater than 65535 are compatible.

unsigned int x=65536;

The value assigned is greater by 1 than the range. Here, the compiler starts again from beginning after reaching the end of the range.

Consider the following example.

2.8  Write a program to demonstrate wrapping around.

void main()

{

unsigned u=65537;

clrscr();

printf(“\n u=%u”,u);

}

OUTPUT:

u=1

Explanation:

In this program, the unsigned integer u = 65537; after reaching the last range 65535, the compiler starts from beginning. Hence, 1 is displayed. The value 65536 refers to 0 and 65537 to 1.

2.19  CONSTANT AND VOLATILE VARIABLES

2.19.1  Constant Variable

If we want the value of a certain variable to remain the same or unchanged during the program execution, it can be done by declaring the variable as a constant. The keyword const is then prefixed before the declaration. It tells the compiler that the variable is a constant. Thus, constant declared variables are protected from modification.

Example:

const int m=10;

Where const is a keyword, m is variable name and 10 is a constant.

The compiler protects the value of ‘m’ from modification. The user cannot assign any value to ‘m’, but using pointer the value can be changed. When user attempts to modify the value of constant variable, the message ‘cannot modify the constant object’ will be displayed.

 

void main()

{

const int num=12;

++num;

}

The above program code will not be executed and end with error message. Here, a constant variable attempted to modify its value.

2.19.2  Volatile Variable

The volatile variables are those variables that can be changed at any time by other external program or the same program. The syntax is as follows:

 

volatile int d;

A program on the above concepts is given below.

2.9  Write a program to demonstrate wrapping around.

void main()

{

volatile int x;

volatile const int y=10;

clrscr();

printf(“Enter an integer:”);

scanf(“%d”,&x);

printf(“Entered integer is :%d”,x);

x=3;

printf(“\nChanged value of x is :%d”,x);

printf(“\nValue of y:%d”,y);

/* y=8;*/

getche();

}

OUTPUT:

Enter an integer:5

Entered integer is :5

Changed value of x is :3

Value of y:10

Explanation:

In the above example, the variable x is initialized with keyword volatile and y is with volatile constant. Value of x can be changed but volatile const can not be changed. Make an attempt to include the comment statement in the program and see the response of the compiler. The error would be thrown by the compiler and message displayed on the screen would be ‘cannot modify a const value’.

SUMMARY

After having studied the basics in the first chapter, the reader is now exposed to, in this second chapter, the additional fundamentals of C. These concepts are absolutely essential for writing programs. Readers are suggested go in depth of this chapter as it contains the fundamentals and basics. The reader is made aware of the following points:

  1. Different types of characters like letters, digits, white space and special characters. Various delimiters used with C statements, keywords and identifies.
  2. Different constants, variables and data types.
  3. Rules for defining variables and initializing them. Also initialization of variables at run time (dynamic initialization) is studied.
  4. Type conversion of variable, type modifiers, wrapping around. Constant and volatile variables.
EXERCISES

I  True or false:

  1. Data means the combination of letters, digits, symbols.
  2. In C, A to Z and a to z are treated as the same.
  3. The signed is a C keyword.
  4. The new is a C keyword.
  5. 10.120 is a integer constant.
  6. Identifiers are the name of variables, arrays, functions, and so on.
  7. The constant in C is applicable to values which do not change during program execution.
  8. ‘A’ is a character constant.
  9. “India” is a string constant.
  10. A variable is a data name used for storing data values.
  11. A value of variable can be changed during the program execution.
  12. A variable name can start with a digit.
  13. The keyword can act as a variable name.
  14. In C the variable name sum & Sum are the same.
  15. short int and int are different from each other.
  16. int, short int and long int belong to one category with different size and range of values.
  17. int occupies 4 bytes in memory.
  18. const int a=10; value of a cannot bechanged during program execution.
  19. _abc is a valid variable name.

II  Select the appropriate option from the multiple choices given below:

  1. A character variable can store only
    1. one character
    2. 20 character
    3. 254 character
    4. None of the above
  2. A C variable cannot start with
    1. a number
    2. an alphabet
    3. a character
    4. None of the above
  3. A short integer variable occupies memory of
    1. 1 bytes
    2. 2 byes
    3. 4 bytes
    4. 8 bytes
  4. C keywords are reserved words by
    1. a compiler
    2. an interpreter
    3. header file
    4. Both (b) and (c)
  5. The declaration of C variable can be done
    1. anywhere in the program
    2. in declaration part
    3. in executable part
    4. at the end of a program
  6. In C one statement can declare
    1. only one variables
    2. two variables
    3. 10 variables
    4. any number of variables
  7. The word ‘int’ is a
    1. keyword
    2. password
    3. header file
    4. None of the above
  8. The variables are initialized using
    1. greater than (>)
    2. equal to (=)
    3. twice equal to (==)
    4. an increment operator (++)
  9. An unsigned integer variable contains values
    1. greater or equal to zero
    2. less than zero
    3. only zeros
    4. (d) Both and (b)
  10. The keyword ‘const’ keeps the value of a variable
    1. constant
    2. mutable
    3. variant
    4. None of the above
  11. Identifiers are
    1. user-defined names
    2. reserved keywords
    3. C statements
    4. None of the above
  12. In C every variable has
    1. a type
    2. a name
    3. a value
    4. a size
    5. all of the above
  13. The range of character data type is
    1. −128 to 127
    2. 0 to 255
    3. 0 to 32767
    4. None of the above
  14. An unsigned integer variable occupies memory
    1. 2 byes
    2. 4 bytes
    3. 1 bytes
    4. 8 bytes
  15. In C double type data needs memory of size
    1. 4 bytes
    2. 2 bytes
    3. 10 bytes
    4. None of the above
  16. In C main() is a
    1. function
    2. user created function
    3. string function
    4. any number of variables
  17. The word ‘continue’ is a
    1. keyword
    2. password
    3. header file
    4. None of the above
  18. The volatile variables are those variables that remain/can be
    1. constant
    2. changed at any time
    3. Both of the above
    4. None of the above
  19. In C the statements following main() are enclosed within
    1. {}
    2. ()
    3. <>
    4. None of the above
  20. In C the maximum value of unsigned character is
    1. 255
    2. 127
    3. 65535
    4. none of the above
  21. The range of long signed integer is
    1. −2147483648 to 2147483647
    2. 0 to 255
    3. 0 to 4294967295
    4. None of the above
  22. In C ‘sizeof’ is a/an
    1. variable
    2. operator
    3. keyword
    4. None of the above
  23. Which is the incorrect variable name
    1. else

    2. name

    3. age

    4. cha_r

  24. How many keywords are there in ANSI C?
    1. 32
    2. 33
    3. 42
    4. 15
  25. Integer constants in C can be
    1. positive
    2. negative
    3. positive or negative
    4. None of the above
  26. Which of the following statement is wrong?
    1. 5+5=a;

    2. ss=12.25;

    3. st=‘m’ * ‘b’;

    4. is =‘A’+10;

  27. The ANSI C standard allows a minimum of
    1. 31significant characters in identifier
    2. 8 significant characters in identifier
    3. 25 significant characters in identifier
    4. unlimited characters
  28. In C the first character of the variable should be
    1. an integer
    2. an alphabet
    3. a floating number
    4. None of the above
  29. How many variables can be initialized at a time?
    1. one
    2. two
    3. five
    4. any number of variables
  30. What is the output of the following program?

    void main()

    {

    unsigned long v=-1;

    clrscr();

    printf(“\n %lu”,v);

    }

    1. 4294967295
    2. 0
    3. –1
    4. None of the above
  31. What would be the values of variables c and u?

    void main()

    {

    char c=-127;

    unsigned char u=-127;

    clrscr();

    printf(“\n c=%d u= %d”,c,u);

    }

    1. c=127 u=127
    2. c= –127 u=129
    3. c=127 u=128
    4. None of the above

III  What will be the output/s of the following program/s?

  1. void main()

    {

    char c=90;

    clrscr();

    printf(“%c”,c);

    }

  2. void main()

    {

    unsigned char c=65;

    clrscr();

    printf(“%d %c %d “,c,c,c);

    }

  3. void main()

    {

    unsigned u=2147483647;

    long l=2147483647;

    clrscr();

    printf(“\n u=%u l=%ld”, u,l);

    }

  4. void main()

    {

    float a=3e-1,b=2e-2;

    clrscr();

    printf(“a=%g b=%g”,a,b);

    }

  5. void main()

    {

    int x, a=1e1, b=0;

    clrscr();

    b+=1e1;

    printf(“a= %d b=%d”,a,b);

    }

IV  Find the bug/s in the following program/s:

  1. void main()

    {

    clrscr();

    printf(“\n %d”, 7/2);

    printf(“\n%g”,7.0/2);

    printf(“\n%g”, float7/2);

    getche();

    }

  2. void main()

    {

    volatile d=15;

    const p=25;

    clrscr();

    printf(“%d %d”d+10,p+1);

    getche();

    }

  3. void main()

    {

    unsigned int d=65535;

    unsigned char p=65;

    clrscr();

    printf(“%c %c”,d,p);

    getche();

    }

  4. void main()

    {

    float d=65535.43;

    double p=65789.987654;

    clrscr();

    printf(“%d %d”,d,p);

    getche();

    }

  5. void main()

    {

    float d=1234567.43;

    double p=987654321.1234567;

    clrscr();

    printf(“\n%f %lf”,d,p);

    printf(“\n%d %d”,size of(d),size of(p));

    getche();

    }

  6. #define

    #define N= 90

    main()

    {

      int x=10,p;

      clrscr();

      p=x*N;

      printf(“\n%d “, p);

      getche();

    }

V  Answer the following questions:

  1. What are the different data types?
  2. What are the differences between signed and unsigned data types?
  3. What does we mean by a variable and constant?
  4. Explain different types of constants in C.
  5. What are the C keywords? Elaborate them.
  6. List the rules for declaring a variable.
  7. What are the identifiers?
  8. Explain the methods for initialization of variables.
  9. Explain constants and volatile variables.
  10. Write about space requirement for variables of different data types.
  11. What are the delimiters? Explain their uses.
  12. Is ‘main’ a keyword? Explain.
  13. List any three keywords with their use.
  14. What is the difference between %f and %g control strings? Whether both can be used for representing float numbers?
  15. What do you mean by type conversion? Why is it necessary?
  16. What is wrapping around?
  17. List the name of type modifiers.
  18. What is dynamic initialization?
ANSWERS

I  True or false:

Q

Ans.

1.

T

2.

F

3.

T

4.

F

5.

F

6.

T

7.

T

8.

T

9.

T

10.

T

11.

T

12.

F

13.

F

14.

F

15.

F

16.

T

17.

F

18.

T

19.

T

II  Select the appropriate option from the multiple choices given below:

Q.

Ans.

1.

a

2.

a

3.

b

4.

a

5.

b

6.

d

7.

a

8.

b

9.

a

10.

a

11.

a

12.

b

13.

a

14.

a

15.

d

16.

b

17.

a

18.

b

19.

a

20.

a

21.

a

22.

c

23.

a

24.

a

25.

c

26.

a

27.

a

28.

b

29.

d

30.

a

31.

b

III  What will be the output/s of the following program/s?

Q.

Ans.

1.

Z

2.

65 A 65

3.

u=65535 l=2147483647

4.

a=0.3 b=0.02

5.

a=10 b=10

IV  Find the bug/s in the following program/s:

Q.

Ans.

1.

Float must be enclosed with bracket, then answer will be

3

3.5

3.5

2.

Missing comma (,) in the printf().

Answer after correction 25 26

3.

First %c is to be replaced by %u and then answer will be 65535 A. However, with %c also program runs.

4.

Control string provided is wrong. %f and %lf are needed. Answer would be 65535.429688 65789.987654. However, with %d & %d answers obtained would be wrong.

5.

Space between size and of should be removed. The answer will be 1234567.375000 987654321.123457

4 8

6.

Syntex error in first line #define. Remove = . Answer will be 900