Data Types Operators

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 133

1. What substitution should be made to //-Ref such that ptr1 points to variable C?

1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int a = 1, b = 2, c = 3;
int *ptr1 = &a;
int **sptr = &ptr1;
//-Ref
}

a) *sptr = &c;
b) **sptr = &c;
c) *ptr1 = &c;
d) None of the mentioned.
View Answer
Answer:a
2. Which of the following declaration throw run-time error?
a) int **c = &c;
b) int **c = &*c;
c) int **c = **c;
d) None of the mentioned
View Answer
Answer:d
3. Comment on the output of this C code?
1.
2.
3.
4.
5.
6.

#include <stdio.h>
int main()
{
int a = 10;
int **c -= &&a;
}

a) You cannot apply any arithmetic operand to a pointer.


b) We dont have address of an address operator
c) Both (a) and (b)
d) None of the mentioned.
View Answer
Answer:b
4. What is the output of this C code?
1.
2.

#include <stdio.h>
void main()

3.
4.
5.
6.
7.
8.

int k = 5;
int *p = &k;
int **m = &p;
printf("%d%d%d\n", k, *p, **m);

a) 5 5 5
b) 5 5 junk value
c) 5 junk junk
d) Compile time error
View Answer
Answer:a
5. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
void main()
{
int k = 5;
int *p = &k;
int **m = &p;
printf("%d%d%d\n", k, *p, **p);
}

a) 5 5 5
b) 5 5 junk value
c) 5 junk junk
d) Compile time error
View Answer
Answer:d
6. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.

#include <stdio.h>
void main()
{
int k = 5;
int *p = &k;
int **m = &p;
**m = 6;
printf("%d\n", k);
}

a) 5
b) Run time error
c) 6

d) Junk
View Answer
Answer:c
7. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
void main()
{
int a[3] = {1, 2, 3};
int *p = a;
int *r = &p;
printf("%d", (**r));
}

a) 1
b) Compile time error
c) Address of a
d) Junk value
View Answer
Answer:b

1. Questions on Data Types, Operators and Expressions in C


Variable Names 1
Data Types and Sizes 1
Constants 1
Declarations 1
Arithmetic Operators 1
Relational & Logical Operators 1
Type Conversions 1
Increment and Decrement Operators 1
Bitwise Operators 1
Assigment Operators & Expressions 1
Conditional Expressions 1
Precedence and Order of Evaluation 1
Precedence and Order of Evaluation 2
Precedence and Order of Evaluation 3

Variable Names 2
Data Types and Sizes 2
Constants 2
Declarations 2
Arithmetic Operators 2
Relational & Logical Operators 2
Type Conversions 2
Increment and Decrement Operators 2
Bitwise Operators 2
Assigment Operators & Expressions 2
Conditional Expressions 2
Precedence and Order of Evaluation 4
Precedence and Order of Evaluation 5
Precedence and Order of Evaluation 6

2. Questions & Answers on Control Flow Statements in C


If-then-else Statements 1
Switch Statements 1
For Loops 1
While Loops 1
Break and Continue 1
Goto & Labels 1

If-then-else Statements 2
Switch Statements 2
For Loops 2
While Loops 2
Break and Continue 2
Goto & Labels 2

3. Questions on C Functions and Structure of a Program


Basics of Functions 1
Functions Returning Non-integers 1
External Variables 1
Scope of a Variable 1
Static Variables 1
Register Variables 1
Automatic Variables 1
C-Preprocessor 1
File Inclusion 1
Macro Substitution 1
Conditional Inclusion 1

Basics of Functions 2
Functions Returning Non-integers 2
External Variables 2
Scope of a Variable 2
Static Variables 2
Register Variables 2
Automatic Variables 2
C-Preprocessor 2
File Inclusion 2
Macro Substitution 2
Conditional Inclusion 2

4. Questions & Answers on Pointers and Arrays in C


Pointers and Addresses 1
Pointers and Function Arguments 1
Pointers and Arrays 1
Address Arithmetic 1

Pointers and Addresses 2


Pointers and Function Arguments 2
Pointers and Arrays 2
Address Arithmetic 2

Character Pointers and Functions 1


Pointers to Pointers 1
Multidimensional Arrays 1
Initialization of Pointer Arrays 1
Pointers Vs. Multi-dimensional Arrays 1
Command Line Arguments 1
Pointers to Functions 1
Complicated Declarations 1

Character Pointers and Functions 2


Pointers to Pointers 2
Multidimensional Arrays 2
Initialization of Pointer Arrays 2
Pointers Vs. Multi-dimensional Arrays 2
Command Line Arguments 2
Pointers to Functions 2
Complicated Declarations 2

5. Questions on Structures, Unions and Bit-Fields in C


Basics of Structures 1
Structures and Functions 1
Arrays of Structures 1
Pointer to Structures 1
Self-Referential Structures 1
Table Lookup 1
Typedefs 1
Unions 1
Bit-fields 1

Basics of Structures 2
Structures and Functions 2
Arrays of Structures 2
Pointer to Structures 2
Self-Referential Structures 2
Table Lookup 2
Typedefs 2
Unions 2
Bit-fields 2

6. Questions & Answers on Input and Output in C


Standard Input & Output 1
Formatted Output 1
Variable Length Argument 1
Formatted Input 1
File Access 1
Error Handling 1
Line Input & Output 1
String Operations 1
Character Class Testing & Conversions 1
Ungetc 1
Storage Management 1
Mathematical Functions 1
Random Number Generation 1

Standard Input & Output 2


Formatted Output 2
Variable Length Argument 2
Formatted Input 2
File Access 2
Error Handling 2
Line Input & Output 2
String Operations 2
Character Class Testing & Conversions 2
Ungetc 2
Storage Management 2
Mathematical Functions 2
Random Number Generation 2

7. Questions on Floating Point & Sizeof Operator in C


Float Datatype 1
Sizeof 1

Float Datatype 2
Sizeof 2

Sample C Programming Questions & Answers:


1. Comment on the output of following code:

1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
main()
{
char *p = 0;
*p = 'a';
printf("value in pointer p is %c\n", *p);
}

a) It will print a
b) It will print 0
c) Compile time error
d) Run time error
View Answer
Answer:d
Output:
$ cc pgm.c
$ a.out
Segmentation fault (core dumped)
2. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
main()
{
if (sizeof(int) > -1)
printf("True");
else
printf("False");
}

a) True
b) False
View Answer
Answer:b
Output:
$ cc pgm.c
$ a.out
False
3. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
main()
{
char *p = "Sanfoundry C-Test";
p[0] = 'a';
p[1] = 'b';
printf("%s", p);

8.

a) abnfoundry C-Test
b) Sanfoundry C-Test
c) Compile time error
d) Run time error
View Answer
Answer:d
Output:
$ cc pgm.c
$ a.out
Segmentation fault (core dumped)
4. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.

#include <stdio.h>
int main()
{
float f = 0.1;
if (f == 0.1)
printf("True");
else
printf("False");
}

a) True
b) False
View Answer
Answer:a
Output:
$ cc pgm.c
$ a.out
False
5. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

#include <stdio.h>
main()
{
int n = 0, m = 0;
if (n > 0)
if (m > 0)
printf("True");
else
printf("False");
}

a) True
b) False
c) No Output will be printed
d) Run Time Error
View Answer
Answer:c
Output:
$ cc pgm.c
$ a.out
$

Questions on Data Types, Operators and Expressions in C


C Programming Questions and Answers Variable Names 1
1. C99 standard guarantees uniqueness of ____ characters for internal names.
a) 31
b) 63
c) 12
d) 14
View Answer
Answer:b
Explanation:ISO C99 compiler may consider only first 63 characters for internal.
2. C99 standard guarantess uniqueness of _____ characters for external names.
a) 31
b) 6
c) 12
d) 14
View Answer
Answer:a
Explanation:ISO C99 compiler may consider only first 31 characters for external
variables having 31 characters due to which it may not be unique.
3. Which of the following is not a valid variable name declaration?
a) int __a3;
b) int __3a;
c) int __A3;
d) None of the mentioned
View Answer
Answer:d
Explanation:None.
4. Which of the following is not a valid variable name declaration?
a) int _a3;
b) int a_3;
c) int 3_a;
d) int _3a
View Answer
Answer:c
Explanation:Variable name cannot start with a digit.

5. Variable names beginning with underscore is not encouraged. Why?


a) It is not standardized
b) To avoid conflicts since assemblers and loaders use such names
c) To avoid conflicts since library routines use such names
d) To avoid conflicts with environment variables of an operating system
View Answer
Answer:c
Explanation:None.
6. All keywords in C are in
a) LowerCase letters
b) UpperCase letters
c) CamelCase letters
d) None
View Answer
Answer:a
Explanation:None.
7. Variable name resolving (number of significant characters for uniqueness of variable)
depends on
a) Compiler and linker implementations
b) Assemblers and loaders implementations
c) C language
d) None
View Answer
Answer:a
Explanation:It depends on the standard to which compiler and linkers are adhering to.
8. Which of the following is not a valid C variable name?
a) int number;
b) float rate;
c) int variable_count;
d) int $main;
View Answer
Answer:d
Explanation:Since only underscore and no other special character is allowed in a variable
name, it results in an error.
9. Which of the following is true for variable names in C?
a) They can contain alphanumeric characters as well as special characters
b) It is not an error to declare a variable to be one of the keywords(like goto, static)

c) Variable names cannot start with a digit


d) Variable can be of any length
View Answer
Answer:c
Explanation:According to the syntax for C variable name, it cannot start with a digit.

1. Which is valid C expression?


a) int my_num = 100,000;
b) int my_num = 100000;
c) int my num = 1000;
d) int $my_num = 10000;
View Answer
Answer:b
Explanation:space, comma and $ cannot be used in a variable name.
2. What is the output of this C code?
1.
2.
3.
4.
5.
6.

#include <stdio.h>
int main()
{
printf("Hello World! %d \n", x);
return 0;
}

a) Hello World! x;
b) Hello World! followed by a junk value
c) Compile time error
d) Hello World!
View Answer
Answer:c
Explanation:It results in an error since x is used without declaring the variable x.
Output:
$ cc pgm1.c
pgm1.c: In function main:
pgm1.c:4: error: x undeclared (first use in this function)
pgm1.c:4: error: (Each undeclared identifier is reported only once
pgm1.c:4: error: for each function it appears in.)
3. What is the output of this C code?
1.
2.

#include <stdio.h>
int main()

3.
4.
5.
6.
7.
8.

int y = 10000;
int y = 34;
printf("Hello World! %d\n", y);
return 0;

a) Compile time error


b) Hello World! 34
c) Hello World! 1000
d) Hello World! followed by a junk value
View Answer
Answer:a
Explanation:Since y is already defined, redefining it results in an error.
Output:
$ cc pgm2.c
pgm2.c: In function main:
pgm2.c:5: error: redefinition of y
pgm2.c:4: note: previous definition of y was here
4. Which of the following is not a valid variable name declaration?
a) float PI = 3.14;
b) double PI = 3.14;
c) int PI = 3.14;
d) #define PI 3.14
View Answer
Answer:d
Explanation:#define PI 3.14 is a macro preprocessor, it is a textual substitution.
5. What will happen if the below program is executed?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int main = 3;
printf("%d", main);
return 0;
}

a) It will cause a compile-time error


b) It will cause a run-time error
c) It will run without any error and prints 3
d) It will experience infinite looping
View Answer
Answer:c
Explanation:A C program can have same function name and same variable name.

$ cc pgm3.c
$ a.out
3
6. What is the problem in following variable declaration?
float 3Bedroom-Hall-Kitchen?;
a) The variable name begins with an integer
b) The special character -
c) The special character ?
d) All of the mentioned
View Answer
Answer:d
Explanation:A variable name cannot start with an integer, along with that the C compiler
interprets the - and ? as a minus operator and a question mark operator respectively.
7. Comment on the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int ThisIsVariableName = 12;
int ThisIsVariablename = 14;
printf("%d", ThisIsVariablename);
return 0;
}

a) The program will print 12


b) The program will print 14
c) The program will have a runtime error
d) The program will cause a compile-time error due to redeclaration
View Answer
Answer:b
Explanation:Variable names ThisIsVariablename and ThisIsVariableName are both
distinct as C is case sensitive.
Output:
$ cc pgm4.c
$ a.out
14
8. Which of the following cannot be a variable name in C?
a) volatile
b) true
c) friend
d) export
View Answer

Answer: a
Explanation:volatile is C keyword.

C Programming Questions and Answers Data Types


and Sizes 1
1. Comment on the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

#include <stdio.h>
int main()
{
int a[5] = {1, 2, 3, 4, 5};
int i;
for (i = 0; i < 5; i++)
if ((char)a[i] == '5')
printf("%d\n", a[i]);
else
printf("FAIL\n");
}

a) The compiler will flag an error


b) Program will compile and print the output 5
c) Program will compile and print the ASCII value of 5
d) Program will compile and print FAIL for 5 times
View Answer
Answer:d
Explanation:The ASCII value of 5 is 53, the char type-casted integral value 5 is 5 only.
Output:
$ cc pgm1.c
$ a.out
FAILED
FAILED
FAILED
FAILED
FAILED
2. The format identifier %i is also used for _____ data type?
a) char
b) int
c) float
d) double
View Answer
Answer:b
Explanation:Both %d and %i can be used as a format identifier for int data type.

3. Which data type is most suitable for storing a number 65000 in a 32-bit system?
a) signed short
b) unsigned short
c) long
d) int
View Answer
Answer:b
Explanation:65000 comes in the range of short (16-bit) which occupies the least memory.
Signed short ranges from -32768 to 32767 and hence we should use unsigned short.
4. Which of the following is a User-defined data type?
a) typedef int Boolean;
b) typedef enum {Mon, Tue, Wed, Thu, Fri} Workdays;
c) struct {char name[10], int age};
d) all of the mentioned
View Answer
Answer:d
Explanation:typedef and struct are used to define user-defined data types.
5. What is the size of an int data type?
a) 4 Bytes
b) 8 Bytes
c) Depends on the system/compiler
d) Cannot be determined
View Answer
Answer:c
Explanation:The size of the data types depend on the system.
6. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
signed char chr;
chr = 128;
printf("%d\n", chr);
return 0;
}

a) 128
b) -128
c) Depends on the compiler
d) None of the mentioned
View Answer

Answer:b
Explanation:signed char will be a negative number.
Output:
$ cc pgm2.c
$ a.out
-128
7. Comment on the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.

#include <stdio.h>
int main()
{
char c;
int i = 0;
FILE *file;
file = fopen("test.txt", "w+");
fprintf(file, "%c", 'a');
fprintf(file, "%c", -1);
fprintf(file, "%c", 'b');
fclose(file);
file = fopen("test.txt", "r");
while ((c = fgetc(file)) != -1)
printf("%c", c);
return 0;
}

a) a
b) Infinite loop
c) Depends on what fgetc returns
d) Depends on the compiler
View Answer
Answer:a
Explanation:None.
Output:
$ cc pgm3.c
$ a.out
a
8. What is short int in C programming?
a) Basic datatype of C
b) Qualifier
c) short is the qualifier and int is the basic datatype
d) All of the mentioned
View Answer
Answer:c
Explanation:None.

1. Comment on the output of this C code?


1.
2.
3.
4.
5.
6.
7.
8.
9.

#include <stdio.h>
int main()
{
float f1 = 0.1;
if (f1 == 0.1)
printf("equal\n");
else
printf("not equal\n");
}

a) equal
b) not equal
c) Output depends on compiler
d) None of the mentioned
View Answer
Answer:b
Explanation:0.1 by default is of type double which has different representation than float
resulting in inequality even after conversion.
Output:
$ cc pgm4.c
$ a.out
not equal
2. Comment on the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.

#include <stdio.h>
int main()
{
float f1 = 0.1;
if (f1 == 0.1f)
printf("equal\n");
else
printf("not equal\n");
}

a) equal
b) not equal
c) Output depends on compiler
d) None of the mentioned
View Answer
Answer:a
Explanation:0.1f results in 0.1 to be stored in floating point representations.
Output:
$ cc pgm5.c
$ a.out
equal

3. What is the output of this C code (on a 32-bit machine)?


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

#include <stdio.h>
int main()
{
int x = 10000;
double y = 56;
int *p = &x;
double *q = &y;
printf("p and q are %d and %d", sizeof(p), sizeof(q));
return 0;
}

a) p and q are 4 and 4


b) p and q are 4 and 8
c) Compiler error
d) p and q are 2 and 8
View Answer
Answer:a
Explanation:Size of any type of pointer is 4 on a 32-bit machine.
Output:
$ cc pgm6.c
$ a.out
p and q are 4 and 4
4. Which is correct with respect to size of the datatypes?
a) char > int > float
b) int > char > float
c) char < int < double
d) double > char > int
View Answer
Answer:c
Explanation:char has lesser bytes than int and int has lesser bytes than double in any
system
5. What is the output of the following C code(on a 64 bit machine)?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

#include <stdio.h>
union Sti
{
int nu;
char m;
};
int main()
{
union Sti s;
printf("%d", sizeof(s));
return 0;

12.

a) 8
b) 5
c) 9
d) 4
View Answer
Answer:d
Explanation:Since the size of a union is the size of its maximum datatype, here int is the
largest hence 4.
Output:
$ cc pgm7.c
$ a.out
4
6. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
float x = 'a';
printf("%f", x);
return 0;
}

a) a
b) run time error
c) a.0000000
d) 97.000000
View Answer
Answer:d
Explanation:Since the ASCII value of a is 97, the same is assigned to the float variable
and printed.
Output:
$ cc pgm8.c
$ a.out
97.000000
7. Which of the datatypes have size that is variable?
a) int
b) struct
c) float
d) double
View Answer

Answer:b
Explanation:Since the size of the structure depends on its fields, it has a variable size.

C Programming Questions and Answers Constants 1


1. What is the output of this C code?
1.
2.
3.
4.
5.
6.

#include <stdio.h>
int main()
{
enum {ORANGE = 5, MANGO, BANANA = 4, PEACH};
printf("PEACH = %d\n", PEACH);
}

a) PEACH = 3
b) PEACH = 4
c) PEACH = 5
d) PEACH = 6
View Answer
Answer:c
Explanation:In enum, the value of constant is defined to the recent assignment from left.
Output:
$ cc pgm1.c
$ a.out
PEACH = 5
2. What is the output of this C code?
1.
2.
3.
4.

#include <stdio.h>
int main()
{
printf("C programming %s", "Class by\n%s Sanfoundry",
"WOW");
5.
}

a) C programming Class by
WOW Sanfoundry
b) C programming Class by\n%s Sanfoundry
c) C programming Class by
%s Sanfoundry
d) Compilation error
View Answer
Answer:c
Explanation:This program has only one %s within first double quotes, so it does not read

the string WOW.


The %s along with the Sanfoundry is not read as a format modifier while new line
character prints the new line.
Output:
$ cc pgm2.c
$ a.out
C programming Class by
%s Sanfoundry
3. For the following code snippet:
char *str = Sanfoundry.com\0 training classes;
The character pointer str holds reference to string:
a) Sanfoundry.com
b) Sanfoundry.com\0training classes
c) Sanfoundry.comtraining classes
d) Invalid declaration
View Answer
Answer:b
Explanation:\0 is accepted as a char in the string. Even though strlen will give length of
string Sanfoundry.com, in memory str is pointing to entire string including training
classes
4. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
#define a 10
int main()
{
const int a = 5;
printf("a = %d\n", a);
}

a) a = 5
b) a = 10
c) Compilation error
d) Runtime error
View Answer
Answer:c
Explanation:The #define substitutes a with 10 leaving no identifier and hence
compilation error.
Output:
$ cc pgm3.c
pgm3.c: In function main:
pgm3.c:5: error: expected identifier or ( before numeric constant
5. What is the output of this C code?

1.
2.
3.
4.
5.
6.

#include <stdio.h>
int main()
{
int var = 010;
printf("%d", var);
}

a) 2
b) 8
c) 9
d) 10
View Answer
Answer:b
Explanation:010 is octal representation of 8.
Output:
$ cc pgm4.c
$ a.out
8
6. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

#include <stdio.h>
enum birds {SPARROW, PEACOCK, PARROT};
enum animals {TIGER = 8, LION, RABBIT, ZEBRA};
int main()
{
enum birds m = TIGER;
int k;
k = m;
printf("%d\n", k);
return 0;
}

a) 0
b) Compile time error
c) 1
d) 8
View Answer
Answer:d
Explanation:m is an integer constant, hence compatible.
Output:
$ cc pgm5.c
$ a.out
8
7. What is the output of this C code?
1.

#include <stdio.h>

2.
3.
4.
5.
6.
7.
8.
9.

#define MAX 2
enum bird {SPARROW = MAX + 1, PARROT = SPARROW + MAX};
int main()
{
enum bird b = PARROT;
printf("%d\n", b);
return 0;
}

a) Compilation error
b) 5
c) Undefined value
d) 2
View Answer
Answer:b
Explanation:MAX value is 2 and hence PARROT will have value 3 + 2.
Output:
$ cc pgm6.c
$ a.out
5
8. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

#include <stdio.h>
#include <string.h>
int main()
{
char *str = "x";
char c = 'x';
char ary[1];
ary[0] = c;
printf("%d %d", strlen(str), strlen(ary));
return 0;
}

a) 1 1
b) 2 1
c) 2 2
d) 1 (undefined value)
View Answer
Answer:d
Explanation:str is null terminated but ary is not.
Output:
$ cc pgm7.c
$ a.out
15

1. enum types are processed by


a) Compiler
b) Preprocessor
c) Linker
d) Assembler
View Answer
Answer:a
Explanation:None.
2. What is the output of this C code?
1.
2.
3.
4.
5.
6.

#include <stdio.h>
int main()
{
printf("sanfoundry\rclass\n");
return 0;
}

a) sanfoundryclass
b) sanfoundry
class
c) classundry
d) sanfoundry
View Answer
Answer:c
Explanation:r is carriage return and moves the cursor back. sanfo is replaced by class
Output:
$ cc pgm8.c
$ a.out
classundry
3. What is the output of this C code?
1.
2.
3.
4.
5.
6.

#include <stdio.h>
int main()
{
printf("sanfoundry\r\nclass\n");
return 0;
}

a) sanfoundryclass
b) sanfoundry
class
c) classundry
d) sanfoundry

View Answer
Answer:b
Explanation:rn combination makes cursor move to nextline.
Output:
$ cc pgm9.c
$ a.out
sanfoundry
class
4. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
const int p;
p = 4;
printf("p is %d", p);
return 0;
}

a) p is 4
b) Compile time error
c) Run time error
d) p is followed by a garbage value
View Answer
Answer:b
Explanation:Since the constant variable has to be declared and defined at the same time,
not doing it results in an error.
Output:
$ cc pgm10.c
pgm10.c: In function main:
pgm10.c:5: error: assignment of read-only variable p
5. Comment on the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.

#include <stdio.h>
void main()
{
int k = 4;
int *const p = &k;
int r = 3;
p = &r;
printf("%d", p);
}

a) Address of k
b) Address of r

c) Compile time error


d) Adress of k + address of r
View Answer
Answer:c
Explanation:Since the pointer p is declared to be constant, trying to assign it with a new
value results in an error.
Output:
$ cc pgm11.c
pgm11.c: In function main:
pgm11.c:7: error: assignment of read-only variable p
pgm11.c:8: warning: format %d expects type int, but argument 2 has type int * const
6. Which is false?
a) Constant variables need not be defined as they are declared and can be defined later
b) Global constant variables are initialised to zero
c) const keyword is used to define constant values
d) You cannot reassign a value to a constant variable
View Answer
Answer:a
Explanation:Since the constant variable has to be declared and defined at the same time,
not doing it results in an error.
Hence the statement a is false.
7. Comment on the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
int const k = 5;
k++;
printf("k is %d", k);
}

a) k is 6
b) Error due to const succeeding int
c) Error, because a constant variable can be changed only twice
d) Error, because a constant variable cannot be changed
View Answer
Answer:d
Explanation:Constant variable has to be declared and defined at the same time. Trying to
change it results in an error.
Output:
$ cc pgm12.c
pgm12.c: In function main:
pgm12.c:5: error: increment of read-only variable k

8. Comment on the output of this C code?


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

#include <stdio.h>
int const print()
{
printf("Sanfoundry.com");
return 0;
}
void main()
{
print();
}

a) Error because function name cannot be preceded by const


b) Sanfoundry.com
c) Sanfoundry.com is printed infinite times
d) Blank screen, no output
View Answer
Answer:b
Explanation:None.
Output:
$ cc pgm13.c
$ a.out
Sanfoundry.com

C Programming Questions and Answers Declarations


1
1. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.

#include <stdio.h>
void foo(const int *);
int main()
{
const int i = 10;
printf("%d ", i);
foo(&i);
printf("%d", i);
}
void foo(const int *i)
{
*i = 20;
}

a) Compile time error


b) 10 20

c) Undefined value
d) 10
View Answer
Answer:a
Explanation:Cannot change a const type value.
Output:
$ cc pgm1.c
pgm1.c: In function foo:
pgm1.c:13: error: assignment of read-only location *i
2. Comment on the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.

#include <stdio.h>
int main()
{
const int i = 10;
int *ptr = &i;
*ptr = 20;
printf("%d\n", i);
return 0;
}

a) Compile time error


b) Compile time warning and printf displays 20
c) Undefined behaviour
d) 10
View Answer
Answer:b
Explanation:Changing const variable through non-constant pointers invokes compiler
warning
Output:
$ cc pgm2.c
pgm2.c: In function main:
pgm2.c:5: warning: initialization discards qualifiers from pointer target type
$ a.out
20
3. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
j = 10;
printf("%d\n", j++);
return 0;
}

a) 10
b) 11
c) Compile time error
d) 0
View Answer
Answer:c
Explanation:Variable j is not defined.
Output:
$ cc pgm3.c
pgm3.c: In function main:
pgm3.c:4: error: j undeclared (first use in this function)
pgm3.c:4: error: (Each undeclared identifier is reported only once
pgm3.c:4: error: for each function it appears in.)
4. Does this compile without error?
1.
2.
3.
4.
5.
6.

#include <stdio.h>
int main()
{
for (int k = 0; k < 10; k++);
return 0;
}

a) Yes
b) No
c) Depends on the C standard implemented by compilers
d) None of the mentioned
View Answer
Answer:c
Explanation:Compilers implementing C90 does not allow this but compilers
implementing C99 allow it.
Output:
$ cc pgm4.c
pgm4.c: In function main:
pgm4.c:4: error: for loop initial declarations are only allowed in C99 mode
pgm4.c:4: note: use option -std=c99 or -std=gnu99 to compile your code
5. Does this compile without error?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int k;
{
int k;
for (k = 0; k < 10; k++);
}

9.

a) Yes
b) No
c) Depends on the compiler
d) Depends on the C standard implemented by compilers
View Answer
Answer:a
Explanation:There can be blocks inside block and within blocks variables have only
block scope.
Output:
$ cc pgm5.c
6. Which of the following declaration is not supported by C?
a) String str;
b) char *str;
c) float str = 3e2;
d) Both (a) and (c)
View Answer
Answer:a
Explanation:It is legal in Java, not in C.
7.
1.
2.
3.
4.
5.

#include <stdio.h>
int main()
{
char *var = "Advanced Training in C by Sanfoundry.com";
}

Which of the following format identifier can never be used for the variable var?
a) %f
b) %d
c) %c
d) %s
View Answer
Answer:a
Explanation:%c can be used to print the indexed position. %d can still be used to display
its ASCII value. %s is recommended.
%f cannot be used.
1. Which of the following declaration is illegal?
a) char *str = Best C programming classes by Sanfoundry;

b) char str[] = Best C programming classes by Sanfoundry;


c) char str[20] = Best C programming classes by Sanfoundry;
d) char[] str = Best C programming classes by Sanfoundry;
View Answer
Answer:d
Explanation:char[] str is a declaration in Java, not in C.
2. Which keyword is used to prevent any changes in the variable within a C program?
a) immutable
b) mutable
c) const
d) volatile
View Answer
Answer:c
Explanation:const is a keyword constant in C program.
3. Which of the following is not a pointer declaration?
a) char a[10];
b) char a[] = {1, 2, 3, 4};
c) char *str;
d) char a;
View Answer
Answer:d
Explanation:Array declarations are pointer declarations.
4. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
int k = 4;
float k = 4;
printf("%d", k)
}

a) Compile time error


b) 4
c) 4.0000000
d) 4.4
View Answer
Answer:a
Explanation:Since the variable k is defined both as integer and as float, it results in an
error.
Output:

$ cc pgm8.c
pgm8.c: In function main:
pgm8.c:5: error: conflicting types for k
pgm8.c:4: note: previous definition of k was here
pgm8.c:6: warning: format %d expects type int, but argument 2 has type double
pgm8.c:7: error: expected ; before } token
5. Which is false ?
a) A variable defined once can be defined again with different scope
b) A single variable cannot be defined with two different types in the same scope
c) A variable must be declared and defined at the same time
d) A variable refers to a location in memory
View Answer
Answer:c
Explanation:It is not an error if the variable is declared and not defined. For example
extern declarations.
6. A variable declared in a function can be used in main
a) True
b) False
c) True if it is declared static
d) None of the mentioned
View Answer
Answer:b
Explanation:Since the scope of the variable declared within a function is restricted only
within that function,
the above statement is false.
7. The name of the variable used in one function cannot be used in another function
a) True
b) False
c) May be
d) None of the mentioned
View Answer
Answer:b
Explanation:Since the scope of the variable declared within a function is restricted only
within that function, the same name can be used to declare another variable in another
function.

C Programming Questions and Answers Arithmetic


Operators 1
1. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int i = -3;
int k = i % 2;
printf("%d\n", k);
}

a) Compile time error


b) -1
c) 1
d) Implementation defined
View Answer
Answer:b
2. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.

#include <stdio.h>
int main()
{
int i = 3;
int l = i / -2;
int k = i % -2;
printf("%d %d\n", l, k);
return 0;
}

a) Compile time error


b) -1 1
c) 1 -1
d) Implementation defined
View Answer
Answer:b
3. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int i = 5;
i = i / 3;
printf("%d\n", i);
return 0;

8.

a) Implementation defined
b) 1
c) 3
d) Compile time error
View Answer
Answer:b
4. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int i = -5;
i = i / 3;
printf("%d\n", i);
return 0;
}

a) Implementation defined
b) -1
c) -3
d) Compile time error
View Answer
Answer:b
5. What is the value of x in this C code?
1.
2.
3.
4.
5.

#include <stdio.h>
void main()
{
int x = 5 * 9 / 3 + 9;
}

a) 3.75
b) Depends on compiler
c) 24
d) 3
View Answer
Answer:c
6. What is the output of this C code?
1.
2.

#include <stdio.h>
void main()

3.
4.
5.
6.

{
}

int x = 5.3 % 2;
printf("Value of x is %d", x);

a) Value of x is 2.3
b) Value of x is 1
c) Value of x is 0.3
d) Compile time error
View Answer
Answer:d
7. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
int y = 3;
int x = 5 % 2 * 3 / 2;
printf("Value of x is %d", x);
}

a) Value of x is 1
b) Value of x is 2
c) Value of x is 3
d) Compile time error
View Answer
Answer:a
1. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
int a = 3;
int b = ++a + a++ + --a;
printf("Value of b is %d", b);
}

a) Value of x is 12
b) Value of x is 13
c) Value of x is 10
d) Undefined behaviour
View Answer
Answer:d

2. The precedence of arithmetic operators is (from highest to lowest)


a) %, *, /, +, b) %, +, /, *, c) +, -, %, *, /
d) %, +, -, *, /
View Answer
3. Which of the following is not an arithmetic operation?
a) a *= 10;
b) a /= 10;
c) a != 10;
d) a %= 10;
View Answer
Answer:c
4. Which of the following data type will throw an error on modulus operation(%)?
a) char
b) short
c) int
d) float
View Answer
5. Which among the following are the fundamental arithmetic operators, ie, performing
the desired operation can be done using that operator only?
a) +, b) +, -, %
c) +, -, *, /
d) +, -, *, /, %
View Answer
Answer:a
6. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.

a) 15
b) 16
c) 15.6

#include <stdio.h>
int main()
{
int a = 10;
double b = 5.6;
int c;
c = a + b;
printf("%d", c);
}

d) 10
View Answer
Answer:a
7. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int a = 10, b = 5, c = 5;
int d;
d = a == (b + c);
printf("%d", d);
}

a) Syntax error
b) 1
c) 10
d) 5
View Answer
Answer: b

C Programming Questions and Answers Relational &


Logical Operators 1
1. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
int x = 1, y = 0, z = 5;
int a = x && y || z++;
printf("%d", z);
}

a) 6
b) 5
c) 0
d) Varies
View Answer
Answer:a
2. What is the output of this C code?

1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
int x = 1, y = 0, z = 5;
int a = x && y && z++;
printf("%d", z);
}

a) 6
b) 5
c) 0
d) Varies
View Answer
Answer:b
3. What is the output of this C code?
1.
2.
3.
4.
5.
6.

#include <stdio.h>
int main()
{
int x = 1, y = 0, z = 3;
x > y ? printf("%d", z) : return z;
}

a) 3
b) 1
c) Compile time error
d) Run time error
View Answer
Answer:c
4. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
int x = 1, z = 3;
int y = x << 3;
printf(" %d\n", y);
}

a) -2147483648
b) -1
c) Run time error
d) 8
View Answer
Answer:d

5. What is the output of this C code?


1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
int x = 0, y = 2, z = 3;
int a = x & y | z;
printf("%d", a);
}

a) 3
b) 0
c) 2
d) Run time error
View Answer
Answer:a
6. What is the final value of j in the below code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int i = 0, j = 0;
if (i && (j = i + 10))
//do something
;
}

a) 0
b) 10
c) Depends on the compiler
d) Depends on language standard
View Answer
Answer:a
7. What is the final value of j in the below code?
1.
2.
3.
4.
5.
6.
7.
8.

a) 0
b) 20

#include <stdio.h>
int main()
{
int i = 10, j = 0;
if (i || (j = i + 10))
//do something
;
}

c) Compile time error


d) Depends on language standard
View Answer
Answer:a
8. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.

#include <stdio.h>
int main()
{
int i = 1;
if (i++ && (i == 1))
printf("Yes\n");
else
printf("No\n");
}

a) Yes
b) No
c) Depends on the compiler
d) Depends on the standard
View Answer
Answer:b
1. Are logical operators sequence points?
a) True
b) False
c) Depends on the compiler
d) Depends on the standard
View Answer
Answer:a
2. Does logical operators in C language are evaluated with short circuit?
a) True
b) False
c) Depends on the compiler
d) Depends on the standard
View Answer
Answer:a
3. Result of a logical or relational expression in C is
a) True or False
b) 0 or 1

c) 0 if expression is false and any positive number if expression is true


d) None of the mentioned
View Answer
Answer:b
4. What will be the value of d in the following program?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int a = 10, b = 5, c = 5;
int d;
d = b + c == a;
printf("%d", d);
}

a) Syntax error
b) 1
c) 5
d) 10
View Answer
Answer:b
5. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int a = 10, b = 5, c = 3;
b != !a;
c = !!a;
printf("%d\t%d", b, c);
}

a) 5 1
b) 0 3
c) 5 3
d) 1 1
View Answer
Answer:a
6. Which among the following is NOT a logical or relational operator?
a) !=
b) ==
c) ||

d) =
View Answer
Answer:d
7. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

#include <stdio.h>
int main()
{
int a = 10;
if (a == a--)
printf("TRUE 1\t");
a = 10;
if (a == --a)
printf("TRUE 2\t");
}

a) TRUE 1
b) TRUE 2
c) TRUE 1 TRUE 2
d) Compiler Dependent
View Answer
Answer:d
Explanation: This is a sequence point problem and hence the result will be
implementation dependent
8. Relational operators cannot be used on:
a) structure
b) long
c) strings
d) float
View Answer
Answer: a

C Programming Questions and Answers Type


Conversions 1
1. What is the output of this C code?
1.
2.
3.
4.

#include <stdio.h>
void main()
{
float x = 0.1;

5.
6.
7.
8.
9.

if (x == 0.1)
printf("Sanfoundry");
else
printf("Advanced C Classes");
}

a) Advanced C Classes
b) Sanfoundry
c) Run time error
d) Compile time error
View Answer
Answer:a
2. Comment on the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
float x = 0.1;
printf("%d, ", x);
printf("%f", x);
}

a) 0.100000, junk value


b) Junk value, 0.100000
c) 0, 0.100000
d) 0, 0.999999
View Answer
Answer:b
3. What is the output of this C code?
(7 and 8 are entered)
1.
2.
3.
4.
5.
6.
7.
8.
9.

#include <stdio.h>
void main()
{
float x;
int y;
printf("enter two numbers \n", x);
scanf("%f %f", &x, &y);
printf("%f, %d", x, y);
}

a) 7.000000, 7
b) Run time error
c) 7.000000, junk
d) Varies
View Answer

Answer:c
4. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
void main()
{
double x = 123828749.66;
int y = x;
printf("%d\n", y);
printf("%lf\n", y);
}

a) 0, 0.0
b) 123828749, 123828749.66
c) 12382874, 12382874.0
d) 123828749, 0.000000
View Answer
Answer:d
5. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
int x = 97;
char y = x;
printf("%c\n", y);
}

a) a
b) b
c) 97
d) Run time error
View Answer
Answer:a
6. When double is converted to float, the value is?
a) Truncated
b) Rounded
c) Depends on the compiler
d) Depends on the standard
View Answer
Answer:c
7. What is the output of this C code?

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

#include <stdio.h>
int main()
{
unsigned int i = 23;
signed char c = -23;
if (i > c)
printf("Yes\n");
else if (i < c)
printf("No\n");
}

a) Yes
b) No
c) Depends on the compiler
d) Depends on the operating system
View Answer
Answer:b
8. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

#include <stdio.h>
int main()
{
int i = 23;
char c = -23;
if (i < c)
printf("Yes\n");
else
printf("No\n");
}

a) Yes
b) No
c) Depends on the compiler
d) Depends on the standard
View Answer
Answer:b
1. function tolower(c) defined in library works for
a) Ascii character set
b) Unicode character set
c) Ascii and utf-8 but not EBSIDIC character set
d) Any character set
View Answer
Answer:d

2. What is the output of the below code considering size of short int is 2, char is 1 and int
is 4 bytes?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
short int i = 20;
char c = 97;
printf("%d, %d, %d\n", sizeof(i), sizeof(c), sizeof(c +
i));

return 0;
}

a) 2, 1, 2
b) 2, 1, 1
c) 2, 1, 4
d) 2, 2, 8
View Answer
Answer:c
3. Which type conversion is NOT accepted?
a) From char to int
b) From float to char pointer
c) From negative int to char
d) From double to char
View Answer
Answer:b
Explanation:Conversion of a float to pointer type is not allowed.
4. What will be the data type of the result of the following operation?
(float)a * (int)b / (long)c * (double)d
a) int
b) long
c) float
d) double
View Answer
Answer:d
5. Which of the following type-casting have chances for wrap around?
a) From int to float
b) From int to char
c) From char to short
d) From char to int
View Answer

Answer:b
6. Which of the following typecasting is accepted by C?
a) Widening conversions
b) Narrowing conversions
c) Both
d) None of the mentioned
View Answer
Answer:c
7. When do you need to use type-conversions?
a) The value to be stored is beyond the max limit
b) The value to be stored is in a form not supported by that data type
c) To reduce the memory in use, relevant to the value
d) All of the mentioned
View Answer
Answer: d

C Programming Questions and Answers Increment


and Decrement Operators 1
1. What is the difference between the following 2 codes?
1.
2.
3.
4.
5.
6.
7.
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h> //Program


int main()
{
int d, a = 1, b = 2;
d = a++ + ++b;
printf("%d %d %d", d, a,
}
#include <stdio.h> //Program
int main()
{
int d, a = 1, b = 2;
d = a++ +++b;
printf("%d %d %d", d, a,
}

b);
2

b);

a) No difference as space doesnt make any difference, values of a, b, d are same in both
the case
b) Space does make a difference, values of a, b, d are different
c) Program 1 has syntax error, program 2 is not
d) Program 2 has syntax error, program 1 is not
View Answer

Answer:d
2. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int a = 1, b = 1, c;
c = a++ + b;
printf("%d, %d", a, b);
}

a) a = 1, b = 1
b) a = 2, b = 1
c) a = 1, b = 2
d) a = 2, b = 2
View Answer
Answer:b
3. What is the output of this C code?
1.
2.
3.
4.
5.

#include <stdio.h>
int main()
{
int a = 1, b = 1, d = 1;
printf("%d, %d, %d", ++a + ++a+a++, a++ + ++b, ++d + d++ +
a++);
6.
}

a) 15, 4, 5
b) 9, 6, 9
c) 9, 3, 5
d) Undefined (Compiler Dependent)
View Answer
Answer:d
4. For which of the following, PI++; code will fail?
a) #define PI 3.14
b) char *PI = A;
c) float PI = 3.14;
d) None of the Mentioned
View Answer
Answer:a
5. What is the output of this C code?

1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int a = 10, b = 10;
if (a = 5)
b--;
printf("%d, %d", a, b--);
}

a) a = 10, b = 9
b) a = 10, b = 8
c) a = 5, b = 9
d) a = 5, b = 8
View Answer
Answer:c
6. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int i = 0;
int j = i++ + i;
printf("%d\n", j);
}

a) 0
b) 1
c) 2
d) Compile time error
View Answer
Answer:a
7. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int i = 2;
int j = ++i + i;
printf("%d\n", j);
}

a) 6
b) 5
c) 4
d) Compile time error
View Answer

Answer:a
8. Comment on the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int i = 2;
int i = i++ + i;
printf("%d\n", i);
}

a) = operator is not a sequence point


b) ++ operator may return value with or without side effects
c) it can be evaluated as (i++)+i or i+(++i)
d) Both a and b
View Answer
Answer:a
1. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int i = 0;
int x = i++, y = ++i;
printf("%d % d\n", x, y);
return 0;
}

a) 0, 2
b) 0, 1
c) 1, 2
d) Undefined
View Answer
Answer:a
2. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int i = 10;
int *p = &i;
printf("%d\n", *p++);
}

a) 10
b) 11
c) Garbage value
d) Address of i
View Answer
Answer:a
3. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
int x = 97;
int y = sizeof(x++);
printf("X is %d", x);
}

a) X is 97
b) X is 98
c) X is 99
d) Run time error
View Answer
Answer:a
4. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
void main()
{
int x = 4, y, z;
y = --x;
z = x--;
printf("%d%d%d", x,
}

a) 3 2 3
b) 2 3 3
c) 3 2 2
d) 2 3 4
View Answer
Answer:b
5. What is the output of this C code?
1.
2.

#include <stdio.h>
void main()

y, z);

3.
4.
5.
6.
7.
8.
9.

int x = 4;
int *p = &x;
int *k = p++;
int r = p - k;
printf("%d", r);

a) 4
b) 8
c) 1
d) Run time error
View Answer
Answer:c
6. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
int a = 5, b = -7, c = 0, d;
d = ++a && ++b || ++c;
printf("\n%d%d%d%d", a, b, c, d);
}

a) 6 -6 0 0
b) 6 -5 0 1
c) -6 -6 0 1
d) 6 -6 0 1
View Answer
Answer:d
7. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
int a = -5;
int k = (a++, ++a);
printf("%d\n", k);
}

a) -4
b) -5
c) 4
d) -3
View Answer

Answer:d

C Programming Questions and Answers Bitwise


Operators 1
1. What is the output of this C code?
1.
2.
3.
4.
5.
6.

#include <stdio.h>
int main()
{
int c = 2 ^ 3;
printf("%d\n", c);
}

a) 1
b) 8
c) 9
d) 0
View Answer
Answer: a
2. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
unsigned int a = 10;
a = ~a;
printf("%d\n", a);
}

a) -9
b) -10
c) -11
d) 10
View Answer
Answer:c
3. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
if (7 & 8)
printf("Honesty");
if ((~7 & 0x000f) == 8)
printf("is the best policy\n");
}

a) Honesty is the best policy


b) Honesty
c) is the best policy
d) No output
View Answer
Answer:c
4. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int a = 2;
if (a >> 1)
printf("%d\n", a);
}

a) 0
b) 1
c) 2
d) No Output.
View Answer
Answer:c
5. Comment on the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int i, n, a = 4;
scanf("%d", &n);
for (i = 0; i < n; i++)
a = a * 2;
}

a) Logical Shift left


b) No output
c) Arithmetic Shift right
d) bitwise exclusive OR
View Answer
Answer:b
6. What is the output of this C code?
1.
2.

#include <stdio.h>
void main()

3.
4.
5.
6.
7.

int x = 97;
int y = sizeof(x++);
printf("x is %d", x);

a) x is 97
b) x is 98
c) x is 99
d) Run time error
View Answer
Answer:a
7. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
void main()
{
int x = 4, y, z;
y = --x;
z = x--;
printf("%d%d%d", x, y, z);
}

a) 3 2 3
b) 2 2 3
c) 3 2 2
d) 2 3 3
View Answer
Answer:d
8. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.

#include <stdio.h>
void main()
{
int x = 4;
int *p = &x;
int *k = p++;
int r = p - k;
printf("%d", r);
}

a) 4
b) 8
c) 1
d) Run time error
View Answer

Answer:c
1. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
int a = 5, b = -7, c = 0, d;
d = ++a && ++b || ++c;
printf("\n%d%d%d%d", a, b, c, d);
}

a) 6 -6 0 0
b) 6 -5 0 1
c) -6 -6 0 1
d) 6 -6 0 1
View Answer
Answer:d
2. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
int a = -5;
int k = (a++, ++a);
printf("%d\n", k);
}

a) -3
b) -5
c) 4
d) Undefined
View Answer
Answer:a
3. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int x = 2;
x = x << 1;
printf("%d\n", x);
}

a) 4
b) 1
c) Depends on the compiler
d) Depends on the endianness of the machine
View Answer
Answer:a
4. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int x = -2;
x = x >> 1;
printf("%d\n", x);
}

a) 1
b) -1
c) 2 ^ 31 1 considering int to be 4 bytes
d) Either b or c
View Answer
Answer:b
5. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
if (~0 == 1)
printf("yes\n");
else
printf("no\n");
}

a) yes
b) no
c) Compile time error
d) Undefined
View Answer
Answer:b
6. What is the output of this C code?
1.
2.

#include <stdio.h>
int main()

3.
4.
5.
6.
7.
8.
9.

int x = -2;
if (!0 == 1)
printf("yes\n");
else
printf("no\n");

a) yes
b) no
c) Run time error
d) Undefined
View Answer
Answer:a
7. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

#include <stdio.h>
int main()
{
int y = 0;
if (1 |(y = 1))
printf("y is %d\n", y);
else
printf("%d\n", y);
}

a) y is 1
b) 1
c) Run time error
d) Undefined
View Answer
Answer:a
8. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

#include <stdio.h>
int main()
{
int y = 1;
if (y & (y = 2))
printf("true %d\n", y);
else
printf("false %d\n", y);
}

a) true 2
b) false 2
c) Either option a or option b
d) true 1
View Answer
Answer:c

C Programming Questions and Answers Assigment


Operators & Expressions 1
1. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.

#include <stdio.h>
void main()
{
int x = 0;
if (x = 0)
printf("Its zero\n");
else
printf("Its not zero\n");
}

a) Its not zero


b) Its zero
c) Run time error
d) None
View Answer
Answer:a
2. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
int k = 8;
int x = 0 == 1 && k++;
printf("%d%d\n", x, k);
}

a) 0 9
b) 0 8
c) 1 8
d) 1 9
View Answer
Answer:b

3. What is the output of this C code?


1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
char a = 'a';
int x = (a % 10)++;
printf("%d\n", x);
}

a) 6
b) Junk value
c) Compile time error
d) 7
View Answer
Answer:c
4. What is the output of this C code?
1.
2.
3.
4.
5.

#include <stdio.h>
void main()
{
1 < 2 ? return 1: return 2;
}

a) returns 1
b) returns 2
c) Varies
d) Compile time error
View Answer
Answer:d
5. What is the output of this C code?
1.
2.
3.
4.
5.
6.

#include <stdio.h>
void main()
{
unsigned int x = -5;
printf("%d", x);
}

a) Run time error


b) Aries
c) -5
d) 5
View Answer

Answer:c
6. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int x = 2, y = 1;
x *= x + y;
printf("%d\n", x);
return 0;
}

a) 5
b) 6
c) Undefined behaviour
d) Compile time error
View Answer
Answer:b
7. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int x = 2, y = 2;
x /= x / y;
printf("%d\n", x);
return 0;
}

a) 2
b) 1
c) 0.5
d) Undefined behaviour
View Answer
Answer:a
8. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int x = 1, y = 0;
x &&= y;
printf("%d\n", x);
}

a) Compile time error


b) 1
c) 0
d) Undefined behaviour
View Answer
Answer:a
1. What is the type of the below assignment expression if x is of type float, y is of type
int?
y = x + y;
a) int
b) float
c) There is no type for an assignment expression
d) double
View Answer
Answer:a
2. What is the value of the below assignment expression
(x = foo())!= 1 considering foo() returns 2
a) 2
b) True
c) 1
d) 0
View Answer
Answer:a
3. Operation a = a * b + a can also be written as:
a) a *= b + 1;
b) (c = a * b)!=(a = c + a);
c) a = (b + 1)* a;
d) All of the mentioned
View Answer
Answer:d
4. for c = 2, value of c after c <<= 1;
a) c = 1;
b) c = 2;
c) c = 3;
d) c = 4;
View Answer

Answer:d
5. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int a = 1, b = 2;
a += b -= a;
printf("%d %d", a, b);
}

a) 1 1
b) 1 2
c) 2 1
d) 2 2
View Answer
Answer:c
6. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int a = 4, n, i, result = 0;
scanf("%d", n);
for (i = 0;i < n; i++)
result += a;
}

a) Addition of a and n.
b) Subtraction of a and n.
c) Multiplication of a and n.
d) Division of a and n.
View Answer
Answer:c
7. Which of the following is an invalid assignment operator?
a) a %= 10;
b) a /= 10;
c) a |= 10;
d) None of the mentioned
View Answer
Answer:d

C Programming Questions and Answers Conditional


Expressions 1
1. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int x = 2, y = 0;
int z = (y++) ? y == 1 && x : 0;
printf("%d\n", z);
return 0;
}

a) 0
b) 1
c) Undefined behaviour
d) Compile time error
View Answer
Answer:a
2. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int x = 1;
int y = x == 1 ? getchar(): 2;
printf("%d\n", y);
}

a) Compile time error


b) Whatever character getchar function returns
c) Ascii value of character getchar function returns
d) 2
View Answer
Answer:c
3. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int x = 1;
short int i = 2;
float f = 3;
if (sizeof((x == 2) ? f : i) == sizeof(float))
printf("float\n");

9.
10.
11.

else if (sizeof((x == 2) ? f : i) == sizeof(short int))


printf("short int\n");
}

a) float
b) short int
c) Undefined behaviour
d) Compile time error
View Answer
Answer:a
4. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int a = 2;
int b = 0;
int y = (b == 0) ? a :(a > b) ? (b = 1): a;
printf("%d\n", y);
}

a) Compile time error


b) 1
c) 2
d) Undefined behaviour
View Answer
Answer:c
5. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int y = 1, x = 0;
int l = (y++, x++) ? y : x;
printf("%d\n", l);
}

a) 1
b) 2
c) Compile time error
d) Undefined behaviour
View Answer
Answer:a

6. What is the output of this C code?


1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
void main()
{
int k = 8;
int m = 7;
int z = k < m ? k++ : m++;
printf("%d", z);
}

a) 7
b) 8
c) Run time error
d) None of the mentioned
View Answer
Answer:a
7. Comment on the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
void main()
{
int k = 8;
int m = 7;
int z = k < m ? k = m : m++;
printf("%d", z);
}

a) Run time error


b) 7
c) 8
d) Depends on compiler
View Answer
Answer:b
8. The code snippet below produces
1.
2.
3.
4.
5.

a) returns 1
b) returns 2
c) Varies

#include <stdio.h>
void main()
{
1 < 2 ? return 1 : return 2;
}

d) Compile time error


View Answer
Answer:d
1. The output of the code below is
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
void main()
{
int k = 8;
int m = 7;
k < m ? k++ : m = k;
printf("%d", k);
}

a) 7
b) 8
c) Compile time error
d) Run time error
View Answer
Answer:c
2. The output of the code below is
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
void main()
{
int k = 8;
int m = 7;
k < m ? k = k + 1 : m = m + 1;
printf("%d", k);
}

a) Compile time error


b) 9
c) 8
d) Run time error
View Answer
Answer:a
3. For initialization a = 2, c = 1 the value of a and c after this code will be
c = (c) ? a = 0 : 2;
a) a = 0, c = 0;
b) a = 2, c = 2;
c) a = 2, c = 2;

d) a = 1, c = 2;
View Answer
Answer:a
4. What will be the data type of the expression (a < 50) ? var1 : var2;
provided a = int, var1 = double, var2 = float
a) int
b) float
c) double
d) Cannot be determined
View Answer
Answer:c
5. Which expression has to be present in the following?
exp1 ? exp2 : exp3;
a) exp1
b) exp2
c) exp3
d) All of the mentioned
View Answer
Answer:d
6. Value of c after the following expression (initializations a = 1, b = 2, c = 1):
c += (-c) ? a : b;
a) Syntax Error
b) c = 1
c) c = 2
d) c = 3
View Answer
Answer:c
7. Comment on the following expression?
c = (n) ? a : b; can be rewritten as
a) if (!n)c = b;
else c = a;
b) if (n <= 0)c = b;
else c = a;
c) if (n > 0)c = a;
else c = b;
d) All of the mentioned
View Answer

Answer:a

C Programming Questions and Answers Precedence


and Order of Evaluation 1
1. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.

#include <stdio.h>
int main()
{
reverse(1);
}
void reverse(int i)
{
if (i > 5)
exit(0);
printf("%d\n", i);
return reverse(i++);
}

a) 1 2 3 4 5
b) 1 2 3 4
c) Compile time error
d) Stack overflow
View Answer
Answer:d
2. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.

#include <stdio.h>
void reverse(int i);
int main()
{
reverse(1);
}
void reverse(int i)
{
if (i > 5)
return ;
printf("%d ", i);
return reverse((i++, i));
}

a) 1 2 3 4 5
b) Segmentation fault
c) Compilation error

d) Undefined behaviour
View Answer
Answer:a
3. In expression i = g() + f(), first function called depends on
a) Compiler
b) Associativiy of () operator
c) Precedence of () and + operator
d) Left to write of the expression
View Answer
Answer:a
4. What is the value of i and j in the below code?
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.

#include <stdio.h>
int x = 0;
int main()
{
int i = (f() +
int j = g() ||
}
int f()
{
if (x == 0)
return x
else
return x
}
int g()
{
return x++;
}

g()) || g();
(f() + g());

+ 1;
- 1;

a)i value is 1 and j value is 1


b)i value is 0 and j value is 0
c)i value is 1 and j value is undefined
d)i and j value are undefined
View Answer
Answer:d
5. What is the value of i and j in the below code?
1.
2.
3.
4.
5.
6.

#include <stdio.h>
int x = 0;
int main()
{
int i = (f() + g()) | g(); //bitwise or
int j = g() | (f() + g()); //bitwise or

7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.

}
int f()
{
if (x == 0)
return x + 1;
else
return x - 1;
}
int g()
{
return x++;
}

a) i value is 1 and j value is 1


b) i value is 0 and j value is 0
c) i value is 1 and j value is undefined
d) i and j value are undefined
View Answer
Answer:c
6. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int x = 2, y = 0;
int z = y && (y |= 10);
printf("%d\n", z);
return 0;
}

a) 1
b) 0
c) Undefined behaviour due to order of evaluation
d) 2
View Answer
Answer:b
7. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int x = 2, y = 0;
int z = (y++) ? 2 : y == 1 && x;
printf("%d\n", z);
return 0;
}

a) 0
b) 1
c) 2
d)Undefined behaviour
View Answer
Answer:b
8. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.

#include <stdio.h>
int main()
{
int x = 2, y = 0;
int z;
z = (y++, y);
printf("%d\n", z);
return 0;
}

a) 0
b) 1
c) Undefined behaviour
d) Compilation error
View Answer
Answer:b
9. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.

#include <stdio.h>
int main()
{
int x = 2, y = 0, l;
int z;
z = y = 1, l = x && y;
printf("%d\n", l);
return 0;
}

a) 0
b) 1
c) Undefined behaviour due to order of evaluation can be different
d) Compilation error
View Answer
Answer:b
10. What is the output of this C code?

1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int y = 2;
int z = y +(y = 10);
printf("%d\n", z);
}

a) 12
b) 20
c) 4
d) Either 12 or 20
View Answer
Answer:b
1. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int x = 2, y = 2;
float f = y + x /= x / y;
printf("%d %f\n", x, f);
return 0;
}

a) 2 4.000000
b) Compile time error
c) 2 3.500000
d) Undefined behaviour
View Answer
Answer:b
2. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.

#include <stdio.h>
int main()
{
int x = 1, y = 2;
if (x && y == 1)
printf("true\n");
else
printf("false\n");
}

a) true
b) false
c) Compile time error

d) Undefined behaviour
View Answer
Answer:b
3. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int x = 1, y = 2;
int z = x & y == 2;
printf("%d\n", z);
}

a) 0
b) 1
c) Compile time error
d) Undefined behaviour
View Answer
Answer:b
4. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int x = 3, y = 2;
int z = x /= y %= 2;
printf("%d\n", z);
}

a) 1
b) Compile time error
c) Floating point exception
d) Segmentation fault
View Answer
Answer:c
5. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int x = 3, y = 2;
int z = x << 1 > 5;
printf("%d\n", z);
}

a) 1
b) 0
c) 3
d) Compile time error
View Answer
Answer:a
6. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int x = 3; //, y = 2;
const int *p = &x;
*p++;
printf("%d\n", *p);
}

a) Increment of read-only location compile error


b) 4
c) Some garbage value
d) Undefined behaviour
View Answer
Answer:c
7. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int x = 2, y = 2;
int z = x ^ y & 1;
printf("%d\n", z);
}

a) 1
b) 2
c) 0
d) 1 or 2
View Answer
Answer:b
8. What is the output of this C code?
1.
2.

#include <stdio.h>
int main()

3.
4.
5.
6.
7.

int x = 2, y = 0;
int z = x && y = 1;
printf("%d\n", z);

a) 0
b) 1
c) Compile time error
d) 2
View Answer
Answer:c
9. What is the output of the code given below
1.
2.
3.
4.
5.
6.
7.
8.
9.

#include <stdio.h>
int main()
{
int x = 0, y = 2;
if (!x && y)
printf("true\n");
else
printf("false\n");
}

a) true
b) false
c) Compile time error
d) Undefined behaviour
View Answer
Answer:a
10. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
int main()
{
int x = 0, y = 2;
int z = ~x & y;
printf("%d\n", z);
}

a) -1
b) 2
c) 0
d) Compile time error
View Answer

Answer:b
1. What is the output of this C code?
1.
2.
3.
4.
5.
6.

#include <stdio.h>
void main()
{
int a = 5 * 3 + 2 - 4;
printf("%d", a);
}

a) 13
b) 14
c) 12
d) 1 6
View Answer
Answer:a
2. What is the output of this C code?
1.
2.
3.
4.
5.
6.

#include <stdio.h>
void main()
{
int a = 2 + 4 + 3 * 5 / 3 - 5;
printf("%d", a);
}

a) 7
b) 6
c) 10
d) 9
View Answer
Answer:b
3. What is the output of this C code?
1.
2.
3.
4.
5.
6.

a) 10
b) 2
c) -2

#include <stdio.h>
void main()
{
int a = 5 * 3 % 6 - 8 + 3;
printf("%d", a);
}

d) -3
View Answer
Answer:c
4. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
void main()
{
int b = 6;
int c = 7;
int a = ++b + c--;
printf("%d", a);
}

a) Run time error


b) 15
c) 13
d) 14
View Answer
Answer:d
5. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main(
{
double b = 8;
b++;
printf("%lf", b);
}

a) 9.000000
b) 9
c) 9.0
d) Run time error
View Answer
Answer:a
6. What is the output of this C code?
1.
2.
3.
4.
5.
6.

#include <stdio.h>
void main()
{
double b = 3 % 0 * 1 - 4 / 2;
printf("%lf", b);
}

a) -2
b) Floating point Exception
c) 1
d) None of the mentioned
View Answer
Answer:b
7. What is the output of this C code?
1.
2.
3.
4.
5.
6.

#include <stdio.h>
void main()
{
double b = 5 % 3 & 4 + 5 * 6;
printf("%lf", b);
}

a) 2
b) 30
c) 2.000000
d) Run time error
View Answer
Answer:c
8. What is the output of this C code?
1.
2.
3.
4.
5.
6.

#include <stdio.h>
void main()
{
double b = 3 && 5 & 4 % 3;
printf("%lf", b);
}

a) 3.000000
b) 4.000000
c) 5.000000
d) 1.000000
View Answer
Answer:d
9. What is the output of this C code?
1.
2.
3.
4.
5.

#include <stdio.h>
void main()
{
double b = 5 & 3 && 4 || 5 | 6;
printf("%lf", b);

6.

a) 1.000000
b) 0.000000
c) 7.000000
d) 2.000000
View Answer
Answer:a
10. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
int k = 0;
double b = k++ + ++k + k--;
printf("%d", k);
}

a) 6
b) 1
c) 5
d) undefined
View Answer
Answer:d
1. What is the output of this C code?
1.
2.
3.
4.
5.
6.

#include <stdio.h>
void main()
{
int b = 5 - 4 + 2 * 5;
printf("%d", b);
}

a) 25
b) -5
c) 11
d) None of the mentioned
View Answer
Answer:c
2. What is the output of this C code?
1.

#include <stdio.h>

2.
3.
4.
5.
6.

void main()
{
int b = 5 & 4 & 6;
printf("%d", b);
}

a) 5
b) 6
c) 3
d) 4
View Answer
Answer:d
3. What is the output of this C code?
1.
2.
3.
4.
5.
6.

#include <stdio.h>
void main()
{
int b = 5 & 4 | 6;
printf("%d", b);
}

a) 6
b) 4
c) 1
d) 0
View Answer
Answer:a
4. What is the output of this C code?
1.
2.
3.
4.
5.
6.

#include <stdio.h>
void main()
{
int b = 5 + 7 * 4 - 9 * (3, 2);
printf("%d", b);
}

a) 6
b) 15
c) 13
d) 21
View Answer
Answer:b
5. What is the output of this C code?

1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
int h = 8;
int b = (h++, h++);
printf("%d%d\n", b, h);
}

a) 10 10
b) 10 9
c) 9 10
d) 8 10
View Answer
Answer:c
6. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
int h = 8;
int b = h++ + h++ + h++;
printf("%d\n", h);
}

a) 9
b) 10
c) 12
d) 11
View Answer
Answer:d
7. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.

#include <stdio.h>
void main()
{
int h = 8;
int b = 4 * 6 + 3 * 4 < 3 ? 4 : 3;
printf("%d\n", b);
}

a) 3
b) 33
c) 34
d) Run time error
View Answer

Answer:a
8. What is the output of this C code?
1.
2.
3.
4.
5.
6.

#include <stdio.h>
void main()
{
int a = 2 + 3 - 4 + 8 printf("%d\n", a);
}

5 % 4;

a) 0
b) 8
c) 11
d) 9
View Answer
Answer:b
9. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
void main()
{
char a = '0';
char b = 'm';
int c = a && b || '1';
printf("%d\n", c);
}

a) 0
b) a
c) 1
d) m
View Answer
Answer:c
10. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
void main()
{
char a = 'A';
char b = 'B';
int c = a + b % 3 - 3 * 2;
printf("%d\n", c);
}

a) 65
b) 58
c) 64
d) 59
View Answer
Answer:d

1. Which of the following operators has an associativity from Right to Left?


a) <=
b) <<
c) ==
d) +=
View Answer
Answer:d
2. Which operators of the following have same precedence?
P. "!=", Q. "+=", R. "<<="
a) P and Q
b) Q and R
c) P and R
d) P, Q and R
View Answer
Answer:b
3. Comment on the following statement?
n = 1;
printf("%d, %dn", 3*n, n++);
a) Output will be 3, 2
b) Output will be 3, 1
c) Output will be 6, 1
d) Output is compiler dependent
View Answer
Answer:d
4. Which of the following option is the correct representation of the following code?
e = a * b + c / d * f;
a) e = (a * (b +(c /(d * f))));
b) e = ((a * b) + (c / (d * f)));
c) e = ((a * b) + ((c / d)* f));

d) Both (B) and (C);


View Answer
Answer:d
Explanation:Verified by e = 1 * 2 + 3 / 4 * 5; and then using respective braces according
to the option.
5. What care must be taken during swapping 2 numbers?
b = (b / a);
a = a * b;
b = a / b;
a) Data type should be either of short, int and long
b) Data type should be either of float and double
c) All data types are accepted except for (char *).
d) This code doesn't swap 2 numbers.
View Answer
Answer:b
6. What should be the output of the following program:
1.
2.
3.
4.
5.
6.
7.

#include<stdio.h>
int main()
{
int a = 1, b = 2, c = 3, d = 4, e;
e = c + d = b * a;
printf("%d, %d\n", e, d);
}

a) 7, 4
b) 7, 2
c) 5, 2
d) Syntax error
View Answer
Answer:d
7. Which of the following is the correct order of evaluation for the given expression?
a = w % x / y * z;
a) % / * =
b) / * % =
c) = % * /
d) * % / =
View Answer
Answer:a

8. Which function in the following expression will be called first?


a = func3(6) func2(4, 5) / func1(1, 2, 3);
a) func1();
b) func2();
c) func3();
d) Cannot be predicted.
View Answer
Answer:d
9. Which of the following operator has the highest precedence in the following?
a) ()
b) sizeof
c) *
d) +
View Answer
Answer:a
10. Which of the following is a ternary operator?
a) &&
b) >>=
c) ?:
d) ->
View Answer
Answer:c
1. Which of the following are unary operators?
a) sizeof
b) c) ++
d) All of the mentioned
View Answer
Answer:d
2. Where in C the order of precedence of operators do not exist?
a) Within conditional statements, if, else
b) Within while, do-while
c) Within macro definition
d) None of the mentioned
View Answer
Answer:d

3. Associativity of an operator are:


a) Right to Left
b) Left to Right
c) Random fashion
d) Both (a) and (b)
View Answer
Answer:d
4. Which of the following method are accepted for assignment?
a) 5 = a = b = c = d;
b) a = b = c = d = 5;
c) a = b = 5 = c = d;
d) None of the mentioned
View Answer
Answer:b
5. Which of the following is NOT possible with any 2 operators in C?
a) Different precedence, same associativity
b) Different precedence, different associativity
c) Same precedence, different associativity.
d) All of the mentioned
View Answer
Answer:c
6. Which of the following is possible with any 2 operators in C?
a) Same associativity, different precedence
b) Same associativity, same precedence
c) Different associativity, different precedence
d) All of the mentioned
View Answer
Answer:d
7. Which of the following operators has the lowest precedence?
a) !=
b) &&
c) ?:
d) ,
View Answer
Answer:d
8. Comment on the output of this C code?

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

#include <stdio.h>
int main()
{
int x = 3, i = 0;
do {
x = x++;
i++;
} while (i != 3);
printf("%d\n", x);
}

a) Undefined behaviour
b) Output will be 3
c) Output will be 6
d) Output will be 5
View Answer
Answer:c
9. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.

#include <stdio.h>
int main()
{
int a = -1, b = 4, c = 1, d;
d = ++a && ++b || ++c;
printf("%d, %d, %d, %d\n", a, b, c, d);
return 0;
}

a) 0, 4, 2, 1
b) 0, 5, 2, 1
c) -1, 4, 1, 1
d) 0, 5, 1, 0
View Answer
Answer:a
10. What is the output of this C code?
1.
2.
3.
4.
5.
6.
7.
8.
9.

#include <stdio.h>
int main()
{
int p = 10, q = 20, r;
if (r = p = 5 || q > 20)
printf("%d", r);
else
printf("No Output\n");
}

a) 1
b) 10
c) 20
d) No Output
View Answer
Answer: a

Public Function VowelCount(ByVal InputString As String) As Long


Dim v(9) As String 'Declare an array of 10 elements 0 to 9
Dim vcount As Integer 'This variable will contain number of vowels
Dim flag As Long
Dim strLen As Long
Dim i As Integer
v(0) = "a" 'First element of array is assigned small a
v(1) = "i"
v(2) = "o"
v(3) = "u"
v(4) = "e"
v(5) = "A" 'Sixth element is assigned Capital A
v(6) = "I"
v(7) = "O"
v(8) = "U"
v(9) = "E"
strLen = Len(InputString)
For flag = 1 To strLen 'It will get every letter of entered string and loop
'will terminate when all letters have been examined
For i = 0 To 9 'Takes every elment of v(9) one by one
'Check if current letter is a vowel
If Mid(InputString, flag, 1) = v(i) Then
vcount = vcount + 1 ' If letter is equal to vowel
'then increment vcount by 1
End If
Next i 'Consider next value of v(i)
Next flag 'Consider next letter of the enterd string
VowelCount = vcount

End Function

Private Sub cmd_calc_Click()


If Trim(Text1.Text) = "" Then
numofwords = 0
Text2.Text = numofwords
Exit Sub
End If
Text1.Text = Trim(Text1.Text) ' Remove All Spaces
numofwords = 1
For n = 1 To Len(Text1.Text)
If Mid(Text1.Text, n, 1) = " " Then
numofwords = numofwords + 1
End If
Next n
Text2.Text = numofwords
numofchars = 0
numofchars = numofchars + Len(Text1.Text) - (numofwords - 1)
Text3.Text = numofchars
End Sub
Private Sub cmdclear_Click()
Text1.Text = ""
Text2.Text = ""
End Sub

Dim strToReverse As String


strToReverse = TextBox1.Text
TextBox1.Text = ""
For i As Integer = strToReverse.Length To 1 Step -1

TextBox1.Text &= Mid(strToReverse, i, 1)


Next

Dim i As Integer
Dim Schar As String
Private Sub cmdclear_Click()
Text1.Text = ""
Text2.Text = ""
End Sub
Private Sub cmdext_Click()
End
End Sub
Private Sub cmdrev_Click()
Text1.Text = Trim(Text1.Text)
For i = Len(Text1.Text) To 1 Step -1
Schar = Schar & Mid$(Text1.Text, i, 1)
Next
Text2.Text = Schar
End Sub

Bubble Sort
For i = 0 To List1.ListCount - 1
For j = 0 To List1.ListCount - i - 1
If Val(List1.List(j)) > Val(List1.List(j + 1)) Then
temp = List1.List(j)
List1.List(j) = List1.List(j + 1)
List1.List(j + 1) = temp
End If
Next j
Next i

Insertion Sort
For i = 0 To List1.ListCount
temp = List1.List(i)
For j = i To 1 Step -1
If Val(List1.List(j - 1)) > temp Then
List1.List(j) = List1.List(j - 1)
Else
Exit For
End If
Next j
List1.List(j) = temp
Next i

Selection Sort
For i = 0 To List1.ListCount - 1
For j = i + 1 To List1.ListCount - 1
If Val(List1.List(j)) < Val(List1.List(i)) Then
temp = List1.List(i)
List1.List(i) = List1.List(j)

List1.List(j) = temp
End If

Next j
Next i
End Sub

Dim i As Long
Dim iMin As Long
Dim iMax As Long
Dim varSwap As Variant
Dim blnSwapped As Boolean
iMin = LBound(pvarArray)
iMax = UBound(pvarArray)-1
Do
blnSwapped = False
For i = iMin To iMax
If pvarArray(i) > pvarArray(i + 1) Then
varSwap = pvarArray(i)
pvarArray(i) = pvarArray(i + 1)
pvarArray(i+1) = varSwap
blnSwapped = True
End If
Next
iMax = iMax - 1
Loop Until Not blnSwapped

Dim i As Long
Dim j As Long
Dim iMin As Long
Dim iMax As Long
Dim varSwap As Variant
iMin = LBound(pvarArray)+1
iMax = UBound(pvarArray)
For i = iMin To iMax
varSwap = pvarArray(i)
For j=i To iMin Step-1
If varSwap < pvarArray(j - 1) Then
Else
Exit For
Next j
pvarArray(j) = varSwap
Next i

Dim i As Long
Dim j As Long
Dim iMin As Long
Dim iMax As Long
Dim varSwap As Variant
iMin = LBound(pvarArray)
iMax = UBound(pvarArray)
For i = iMin To iMax - 1
iMin = i
For j = (i + 1) To iMax

pvarArray(j) = pvarArray(j - 1)

If pvarArray(j) < pvarArray(iMin) Then


Next
varSwap = pvarArray(i)
pvarArray(i) = pvarArray(iMin)
pvarArray(iMin) = varSwap
Next

iMin = j

Polymorphism
Before getting any deeper into this chapter, you should have a proper understanding of
pointers and class inheritance. If you are not really sure of the meaning of any of the
following expressions, you should review the indicated sections:
Statement:

Explained in:
Classes
a->b
Data structures
class A: public B {}; Friendship and inheritance
int A::b(int c) { }

Pointers to base class


One of the key features of class inheritance is that a pointer to a derived class is typecompatible with a pointer to its base class. Polymorphism is the art of taking advantage of
this simple but powerful and versatile feature.
The example about the rectangle and triangle classes can be rewritten using pointers
taking this feature into account:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

// pointers to base class


#include <iostream>
using namespace std;
class Polygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
};
class Rectangle: public Polygon {
public:
int area()

20
10

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

{ return width*height; }
};
class Triangle: public Polygon {
public:
int area()
{ return width*height/2; }
};
int main () {
Rectangle rect;
Triangle trgl;
Polygon * ppoly1 = &rect;
Polygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout << rect.area() << '\n';
cout << trgl.area() << '\n';
return 0;
}

Function main declares two pointers to Polygon (named ppoly1 and ppoly2). These are
assigned the addresses of rect and trgl, respectively, which are objects of type
Rectangle and Triangle. Such assignments are valid, since both Rectangle and
Triangle are classes derived from Polygon.
Dereferencing ppoly1 and ppoly2 (with *ppoly1 and *ppoly2) is valid and allows us to
access the members of their pointed objects. For example, the following two statements
would be equivalent in the previous example:
1 ppoly1->set_values (4,5);
2 rect.set_values (4,5);

But because the type of ppoly1 and ppoly2 is pointer to Polygon (and not pointer to
Rectangle nor pointer to Triangle), only the members inherited from Polygon can be
accessed, and not those of the derived classes Rectangle and Triangle. That is why the
program above accesses the area members of both objects using rect and trgl directly,
instead of the pointers; the pointers to the base class cannot access the area members.
Member area could have been accessed with the pointers to Polygon if area were a
member of Polygon instead of a member of its derived classes, but the problem is that
Rectangle and Triangle implement different versions of area, therefore there is not a
single common version that could be implemented in the base class.

Virtual members
A virtual member is a member function that can be redefined in a derived class, while
preserving its calling properties through references. The syntax for a function to become
virtual is to precede its declaration with the virtual keyword:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

// virtual members
#include <iostream>
using namespace std;
class Polygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area ()
{ return 0; }
};
class Rectangle: public Polygon {
public:
int area ()
{ return width * height; }
};

20
class Triangle: public Polygon {
10
public:
0
int area ()
{ return (width * height / 2); }
};

Edit & Run

int main () {
Rectangle rect;
Triangle trgl;
Polygon poly;
Polygon * ppoly1 = &rect;
Polygon * ppoly2 = &trgl;
Polygon * ppoly3 = &poly;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
ppoly3->set_values (4,5);
cout << ppoly1->area() << '\n';
cout << ppoly2->area() << '\n';
cout << ppoly3->area() << '\n';
return 0;
}

In this example, all three classes (Polygon, Rectangle and Triangle) have the same
members: width, height, and functions set_values and area.
The member function area has been declared as virtual in the base class because it is
later redefined in each of the derived classes. Non-virtual members can also be redefined

in derived classes, but non-virtual members of derived classes cannot be accessed


through a reference of the base class: i.e., if virtual is removed from the declaration of
area in the example above, all three calls to area would return zero, because in all cases,
the version of the base class would have been called instead.
Therefore, essentially, what the virtual keyword does is to allow a member of a derived
class with the same name as one in the base class to be appropriately called from a
pointer, and more precisely when the type of the pointer is a pointer to the base class that
is pointing to an object of the derived class, as in the above example.
A class that declares or inherits a virtual function is called a polymorphic class.
Note that despite of the virtuality of one of its members, Polygon was a regular class, of
which even an object was instantiated (poly), with its own definition of member area
that always returns 0.

Abstract base classes


Abstract base classes are something very similar to the Polygon class in the previous
example. They are classes that can only be used as base classes, and thus are allowed to
have virtual member functions without definition (known as pure virtual functions). The
syntax is to replace their definition by =0 (and equal sign and a zero):
An abstract base Polygon class could look like this:
1 // abstract class CPolygon
2 class Polygon {
3
protected:
4
int width, height;
5
public:
6
void set_values (int a, int b)
7
{ width=a; height=b; }
8
virtual int area () =0;
9 };

Notice that area has no definition; this has been replaced by =0, which makes it a pure
virtual function. Classes that contain at least one pure virtual function are known as
abstract base classes.
Abstract base classes cannot be used to instantiate objects. Therefore, this last abstract
base class version of Polygon could not be used to declare objects like:
Polygon mypolygon;

// not working if Polygon is abstract base class

But an abstract base class is not totally useless. It can be used to create pointers to it, and

take advantage of all its polymorphic abilities. For example, the following pointer
declarations would be valid:
1 Polygon * ppoly1;
2 Polygon * ppoly2;

And can actually be dereferenced when pointing to objects of derived (non-abstract)


classes. Here is the entire example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

// abstract base class


#include <iostream>
using namespace std;
class Polygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area (void) =0;
};
class Rectangle: public Polygon {
public:
int area (void)
{ return (width * height); }
};

20
10

Edit & Run

class Triangle: public Polygon {


public:
int area (void)
{ return (width * height / 2); }
};
int main () {
Rectangle rect;
Triangle trgl;
Polygon * ppoly1 = &rect;
Polygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout << ppoly1->area() << '\n';
cout << ppoly2->area() << '\n';
return 0;
}

In this example, objects of different but related types are referred to using a unique type
of pointer (Polygon*) and the proper member function is called every time, just because
they are virtual. This can be really useful in some circumstances. For example, it is even
possible for a member of the abstract base class Polygon to use the special pointer this

to access the proper virtual members, even though Polygon itself has no implementation
for this function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

// pure virtual members can be called


// from the abstract base class
#include <iostream>
using namespace std;
class Polygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area() =0;
void printarea()
{ cout << this->area() << '\n'; }
};
class Rectangle: public Polygon {
public:
int area (void)
{ return (width * height); }
};

20
10

Edit & Run

class Triangle: public Polygon {


public:
int area (void)
{ return (width * height / 2); }
};
int main () {
Rectangle rect;
Triangle trgl;
Polygon * ppoly1 = &rect;
Polygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
ppoly1->printarea();
ppoly2->printarea();
return 0;
}

Virtual members and abstract classes grant C++ polymorphic characteristics, most useful
for object-oriented projects. Of course, the examples above are very simple use cases, but
these features can be applied to arrays of objects or dynamically allocated objects.
Here is an example that combines some of the features in the latest chapters, such as
dynamic memory, constructor initializers and polymorphism:
1 // dynamic allocation and polymorphism
2 #include <iostream>
3 using namespace std;

20
10

Edit & Run

4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

class Polygon {
protected:
int width, height;
public:
Polygon (int a, int b) : width(a), height(b) {}
virtual int area (void) =0;
void printarea()
{ cout << this->area() << '\n'; }
};
class Rectangle: public Polygon {
public:
Rectangle(int a,int b) : Polygon(a,b) {}
int area()
{ return width*height; }
};
class Triangle: public Polygon {
public:
Triangle(int a,int b) : Polygon(a,b) {}
int area()
{ return width*height/2; }
};
int main () {
Polygon * ppoly1 = new Rectangle (4,5);
Polygon * ppoly2 = new Triangle (4,5);
ppoly1->printarea();
ppoly2->printarea();
delete ppoly1;
delete ppoly2;
return 0;
}

Notice that the ppoly pointers:


1 Polygon * ppoly1 = new Rectangle (4,5);
2 Polygon * ppoly2 = new Triangle (4,5);

are declared being of type "pointer to Polygon", but the objects allocated have been
declared having the derived class type directly (Rectangle and Triangle).

Pure Virtual Functions and Abstract Classes in C++


July 15, 2014
Sometimes implementation of all function cannot be provided in a base class because we
dont know the implementation. Such a class is called abstract class. For example, let
Shape be a base class. We cannot provide implementation of function draw() in Shape,
but we know every derived class must have implementation of draw(). Similarly an
Animal class doesnt have implementation of move() (assuming that all animals move),
but all animals must know how to move. We cannot create objects of abstract classes.
A pure virtual function (or abstract function) in C++ is a virtual function for which we
dont have implementation, we only declare it. A pure virtual function is declared by
assigning 0 in declaration. See the following example.
// An abstract class
class Test
{
// Data members of class
public:
// Pure Virtual Function
virtual void show() = 0;
/* Other members */
};

A complete example:
A pure virtual function is implemented by classes which are derived from a Abstract
class. Following is a simple example to demonstrate the same.
#include<iostream>
using namespace std;
class Base
{
int x;
public:
virtual void fun() = 0;

};

int getX() { return x; }

// This class ingerits from Base and implements fun()


class Derived: public Base
{
int y;
public:
void fun() { cout << "fun() called"; }
};
int main(void)
{
Derived d;
d.fun();
return 0;
}

Output:
fun() called

Some Interesting Facts:


1) A class is abstract if it has at least one pure virtual function.
In the following example, Test is an abstract class because it has a pure virtual function
show().
// pure virtual functions make a class abstract
#include<iostream>
using namespace std;
class Test
{
int x;
public:
virtual void show() = 0;
int getX() { return x; }
};
int main(void)
{
Test t;
return 0;
}

Output:
Compiler Error: cannot declare variable 't' to be of abstract
type 'Test' because the following virtual functions are pure
within 'Test': note:
virtual void Test::show()

2) We can have pointers and references of abstract class type.


For example the following program works fine.
#include<iostream>
using namespace std;
class Base
{
public:
virtual void show() = 0;
};
class Derived: public Base
{
public:
void show() { cout << "In Derived \n"; }
};
int main(void)
{
Base *bp = new Derived();
bp->show();
return 0;
}

Output:
In Derived

3) If we do not override the pure virtual function in derived class, then derived class also
becomes abstract class.
The following example demonstrates the same.
#include<iostream>
using namespace std;
class Base
{
public:
virtual void show() = 0;
};
class Derived : public Base { };
int main(void)
{
Derived d;
return 0;
}
Compiler Error: cannot declare variable 'd' to be of abstract type
'Derived' because the following virtual functions are pure within
'Derived': virtual void Base::show()

4) An abstract class can have constructors.


For example, the following program compiles and runs fine.
#include<iostream>
using namespace std;
// An abstract class with constructor
class Base
{
protected:
int x;
public:
virtual void fun() = 0;
Base(int i) { x = i; }
};
class Derived: public Base
{
int y;
public:
Derived(int i, int j):Base(i) { y = j; }
void fun() { cout << "x = " << x << ", y = " << y; }
};
int main(void)
{
Derived d(4, 5);
d.fun();
return 0;
}

Output:
x = 4, y = 5

Comparison with Java


In Java, a class can be made abstract by using abstract keyword. Similarly a function can
be made pure virtual or abstract by using abstract keyword. See
Abstract Classes in Java for more details.
Interface vs Abstract Classes:
An interface does not have implementation of any of its methods, it can be considered as
a collection of method declarations. In C++, an interface can be simulated by making all
methods as pure virtual. In Java, there is a separate keyword for interface.
Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above

An interface describes the behavior or capabilities of a C++ class without committing to a


particular implementation of that class.
The C++ interfaces are implemented using abstract classes and these abstract classes
should not be confused with data abstraction which is a concept of keeping
implementation details separate from associated data.
A class is made abstract by declaring at least one of its functions as pure virtual
function. A pure virtual function is specified by placing "= 0" in its declaration as
follows:
class Box
{
public:
// pure virtual function
virtual double getVolume() = 0;
private:
double length;
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
};

The purpose of an abstract class (often referred to as an ABC) is to provide an


appropriate base class from which other classes can inherit. Abstract classes cannot be
used to instantiate objects and serves only as an interface. Attempting to instantiate an
object of an abstract class causes a compilation error.
Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the
virtual functions, which means that it supports the interface declared by the ABC. Failure
to override a pure virtual function in a derived class, then attempting to instantiate objects
of that class, is a compilation error.
Classes that can be used to instantiate objects are called concrete classes.

Abstract Class Example:


Consider the following example where parent class provides an interface to the base class
to implement a function called getArea():
#include <iostream>
using namespace std;
// Base class
class Shape

{
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived classes
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Triangle: public Shape
{
public:
int getArea()
{
return (width * height)/2;
}
};
int main(void)
{
Rectangle Rect;
Triangle Tri;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;
Tri.setWidth(5);
Tri.setHeight(7);
// Print the area of the object.
cout << "Total Triangle area: " << Tri.getArea() << endl;
}

return 0;

When the above code is compiled and executed, it produces the following result:
Total Rectangle area: 35

Total Triangle area: 17

You can see how an abstract class defined an interface in terms of getArea() and two
other classes implemented same function but with different algorithm to calculate the
area specific to the shape.

Designing Strategy:
An object-oriented system might use an abstract base class to provide a common and
standardized interface appropriate for all the external applications. Then, through
inheritance from that abstract base class, derived classes are formed that all operate
similarly.
The capabilities (i.e., the public functions) offered by the external applications are
provided as pure virtual functions in the abstract base class. The implementations of these
pure virtual functions are provided in the derived classes that correspond to the specific
types of the application.
This architecture also allows new applications to be added to a system easily, even after
the system has been defined.

Starting out
Get the Ebook
Get Started with C
or C++
Getting a Compiler
Book
Recommendations

Tutorials
C Tutorial
C++ Tutorial
Java Tutorial

Example of polymorphism source code


This snippet submitted by Ali Nawkhas Murad on 2012-01-09. It has
been viewed 32639 times.
Rating of 5.5 with 176 votes
1
2
3
4
5
6

//An example of using overriding techniques to


demonstrate function with a polymorphism behaviour.
#include <iostream>
using namespace std;
// abstract base class

Game Programming
Graphics
Programming
Algorithms & Data
Structures
Debugging
All Tutorials

Practice
Practice Problems
Quizzes

Resources
Source Code
Source Code
Snippets
C and C++ Tips
Finding a Job

References
Function Reference
Syntax Reference
Programming FAQ

Getting Help
Message Board
Email
About Us

7 class base
8 {
protected: // attribute section
9
int num1;
10
int num2;
int result;
11
public:
// behavior section
12
void setVar(int n1,int n2)
13
{
14
num1 = n1;
15
num2 = n2;
}
16
virtual void op() = 0; // pure virtual function
17
int getresult() {return result;}
18};
19
20class add: public base // add class inherits from base
21class
22{
23 public:
void op() {result = num1 + num2;}
24};
25
26//sub class inherit base class
27class sub: public base
28{
public:
29
void op() {result = num1 - num2;}
30};
31
32int main()
33{
int x,y;
34
base *m; //pointer variable declaration of type base
35class
36
add ad; //create object1 for addition process
sub su; //create object2 for subtraction process
37
cout << "\nEnter two numbers seperated by space, or
38
press Ctrl+z to Exit: ";
39
40
while(cin >> x >> y)
41
{
42
m = &ad;
m->setVar( x , y );
43
m->op(); //addition process, even though call is
44
on pointer to base!
45
cout << "\nResult of summation = " << m46>getresult();
m = &su;
47
m->setVar( x , y );
48
m->op(); //subtraction process, even though call
49
is on pointer to base!
50
cout << "\nResult of subtraction = " << m51>getresult() << endl << endl;
cout << "\nEnter two numbers seperated by space
52
or press Ctrl+z to Exit: ";

53
54
55
56
}
return 0;
57
}
58
59
/*program output
60****************
61Enter two numbers seperated by space, or press Ctrl+z to
62Exit: 88 9
63
64Result of summation = 97
65Result of subtraction = 79
66
67Enter two numbers seperated by space or press Ctrl+z to
68Exit: ^Z
69
70Process returned 0 (0x0)
execution time : 102.711 s
Press
any
key
to
continue.
71
72*/
73
74
75

MODULE 17 - THE C++ POLYMORPHISM 1

My Training Period: xx hours


The source code for this tutorial is available in C++ Polymorphism source code.
The C++ programming skills that should be acquired:
Able to understand and use:

17.1

17.2

Polymorphism concept.
Virtual function.
Late and early binding.
Introduction
Polymorphism is a technique that allows you to set a base object equal to
one or more of its derived objects.
The interesting thing about this technique is that, after the assignment,
the base acts in different ways, depending on the traits of the derived
object that is currently assigned to it. The base object that acts in many
different ways, hence the name "polymorphism," which translates literally
to "many form."
Another way of looking at polymorphism: A base class defines a certain
number of functions that are inherited by all its descendants. If you
assign a variable of the derived type to one of its base, all the base's
methods are guaranteed to be filled out with valid addresses of the
pointers.
The issue here is that the derived object, by the fact of its being a
descendant object, must have valid addresses for all the methods used in
its bases virtual method table (VMT). As a result, you can call one of
these methods and watch as the derived functions get called.
However, you cannot call one of the derived methods that do not belong
to the base. The base doesn't know about those methods, so the
compiler won't let you call them. In other words, the base may be able to
call some of the derive functions, but it is still a variable of the base type.
A virtual method table, or VMT, is a table maintained in memory by the
compiler; it contains a list of all the pointers to the virtual methods
hosted by an object. If you have an object that is descended from, let say,
TObject, the VMT for that object will contain all the virtual methods of that
object, plus the virtual methods of TObject.
If some of the methods in a base class are defined as virtual, each of the
descendants can redefine the implementation of these methods. The key
elements that define a typical case of polymorphism are a base class
and the descendants that inherit a base class methods. In particular,
the fanciest type of polymorphism involves virtual methods that are
inherited from a base class.
A Simple Program With Inheritance
Examine the program example named poly1.cpp, the basic program that

will be use for our discussion in this Module. The last program in this
Module will illustrate the proper use of virtual functions.
1. // program poly1.cpp
2. #include <iostream>
3. using namespace std;
4.
5. // a base class declaration
6. // and the implementation part
7. class vehicle
8. {
9.
int wheels;
10.
float weight;
11.
public:
12.
void message(void) // first message()
13.
{cout<<"Vehicle message, from vehicle, the base class\n";}
14. };
15.
16. // a derived class declaration and implementation part
17. class car : public vehicle
18. {
19.
int passenger_load;
20.
public:
21.
void message(void) // second message()
22.
{cout<<"Car message, from car, the vehicle derived
class\n";}
23. };
24.
25. class truck : public vehicle
26. {
27.
int passenger_load;
28.
float payload;
29.
public:
30.
int passengers(void) {return passenger_load;}
31. };
32.
33. class boat : public vehicle
34. {
35.
int passenger_load;
36.
public:
37.
int passengers(void) {return passenger_load;}
38.
void message(void) // third message()
39.
{cout<<"Boat message, from boat, the vehicle derived
class\n";}
40. };
41.
42. // the main program

43. int main()


44. {
45.
vehicle unicycle;
46.
car
sedan_car;
47.
truck trailer;
48.
boat sailboat;
49.
50.
unicycle.message();
51.
sedan_car.message();
52.
trailer.message();
53.
sailboat.message();
54.
55.
// base and derived object assignment
56.
unicycle = sedan_car;
57.
unicycle.message();
58.
59.
// system("pause);
60.
return 0;
61. }
61 Lines: Output:

This program is greatly simplified in order to effectively show you the use
of a virtual function. You will notice that many of the methods from the
last Module have been completely dropped from this example for
simplicity, and a new method has been added to the base class, the
method named message() in line 12 as shown below.
void message(void) // first message()
Throughout this Module we will be studying the operation of the method
named message() in the base class and the derived classes. For that
reason, there is another method named message() in the derived car and
boat classes in lines 21 and 38 respectively as shown below:
void message(void) // second message()
...
void message(void) // third message()
You will also notice that there is no method named message() in the truck
class. This has been done on purpose to illustrate the use of the virtual
function/method. You will recall that the method named message() from

17.3

the base class is available in the truck class because the method from the
base class is inherited with the keyword public included in line 25 as
shown below.
class truck : public vehicle
The main() program is as simple as the classes; one object of each of the
classes is defined in lines 45 through 48 as shown below.
vehicle unicycle;
car
sedan_car;
truck trailer;
boat sailboat;
And the method named message() is called once for each object. The
output of this program indicates that the method for each is called except
for the object named trailer, which has no method named message().
The method named message() from the base class is called and the data
output to the screen indicates that this did happen.
Line 56 as shown below indicates how the derived object has been
assigned to the base object,
unicycle = sedan_car;
And then calls the base object again in line 57 as shown below.
unicycle.message();
We are not concern with the data, so all the data is allowed to the default
private type and none is inherited into the derived classes. Some of the
data is left in the program example simply to make the classes look like
classes.
The data could be removed since it is not used. Compile and run this
program to see if your compiler gives a similar result.
Adding The Keyword virtual
Examine the next program example named poly2.cpp, you will notice that
there is one small change in line 12. The keyword virtual has been added
to the declaration of the method named message() in the base class.
1. // program poly2.cpp
2. #include <iostream>
3. using namespace std;
4.
5. // a base class declaration
6. // and the implementation part
7. class vehicle
8. {
9.
int wheels;
10.
float weight;
11.
public:
12.
virtual void message(void)
13.
// first message(), with virtual keyword
14.
{cout<<"Vehicle message, from vehicle, the base class\n";}
15. };
16.

17. // the derived class declaration and implementation part


18. class car : public vehicle
19. {
20.
int passenger_load;
21.
public:
22.
void message(void) // second message()
23.
{cout<<"Car message, from car, the vehicle derived
class\n";}
24. };
25.
26. class truck : public vehicle
27. {
28.
int passenger_load;
29.
float payload;
30.
public:
31.
int passengers(void) {return passenger_load;}
32. };
33.
34. class boat : public vehicle
35. {
36.
int passenger_load;
37.
public:
38.
int passengers(void) {return passenger_load;}
39.
void message(void) // third message()
40.
{cout<<"Boat message, from boat, the vehicle derived
class\n";}
41. };
42.
43. // the main program
44. int main()
45. {
46.
vehicle unicycle;
47.
car
sedan_car;
48.
truck trailer;
49.
boat
sailboat;
50.
51.
cout<<"Adding virtual keyword at the base class method\n";
52.
cout<<"-----------------------------------------------\n";
53.
unicycle.message();
54.
sedan_car.message();
55.
trailer.message();
56.
sailboat.message();
57.
58.
// unicycle = sedan_car;
59.
// sedan_car.message();
60.

61.
62.
63. }

// system("pause");
return 0;

63 Lines: Output:

But this program operates no differently than the last example. This is
because we are using objects directly and virtual methods have nothing
to do with objects, only with pointers to objects as we will see soon.
There is an additional comment in line 59 and 60 as shown below:
// unicycle = sedan_car;
// sedan_car.message();
Illustrating that since all four objects is of different classes, it is impossible
to assign any object to any other object in this program with different
result. We will soon see that some pointer assignments are permitted
between objects of dissimilar classes.
Compile and run this program example to see if your compiler results in
the same output as shown.
17.4 Using Object Pointers
Examine the program example named poly3.cpp and you will find a
repeat of the first program but with a different main program.
1. // program poly3.cpp
2. #include <iostream>
3. using namespace std;
4.
5. // a base class declaration
6. // and the implementation part
7. class vehicle
8. {
9.
int wheels;
10.
float weight;
11.
public:
12.
void message(void)
13.
// first message()
14.
{cout<<"Vehicle message, from vehicle, the base class\n";}
15. };
16.

17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.

// a derived class declaration and implementation part


class car : public vehicle
{
int passenger_load;
public:
void message(void) // second message()
{cout<<"Car message, from car, the vehicle derived class\n";}
};
class truck : public vehicle
{
int passenger_load;
float payload;
public:
int passengers(void) {return passenger_load;}
};

class boat : public vehicle


{
int passenger_load;
public:
int passengers(void) {return passenger_load;}
void message(void) // third message()
{cout<<"Boat message, from boat, the vehicle derived
class\n";}
41. };
42.
43. // the main program
44. int main()
45. {
46.
vehicle *unicycle;
47.
car *sedan_car;
48.
truck *trailer;
49.
boat *sailboat;
50.
51.
cout<<"Omitting the virtual keyword. Using\n";
52.
cout<<"pointer variables, and new keyword\n";
53.
cout<<"-----------------------------------\n";
54.
55.
unicycle = new vehicle;
56.
unicycle->message();
57.
sedan_car = new car;
58.
sedan_car->message();
59.
trailer = new truck;
60.
trailer->message();
61.
sailboat = new boat;

62.
63.
64.
65.
66.
67.
68.
69.
70. }

sailboat->message();
unicycle = sedan_car;
unicycle->message();
// system("pause");
return 0;

70 Lines: Output:

In this program the keyword virtual has been removed from the method
declaration in the base class in line 12, and the main() program defines
pointers to the objects rather than defining the objects themselves in lines
46 through 49 as shown below:
vehicle *unicycle;
car *sedan_car;
truck *trailer;
boat *sailboat;
Since we only defined pointers to the objects, we find it necessary to
allocate the objects before using them by using the new operator in lines
55, 57, 59 and 61 as shown below:
unicycle = new vehicle;
...
sedan_car = new car;
...
trailer = new truck;
...
sailboat = new boat;
Upon running the program, we find that even though we are using
pointers to the objects, we have done nothing different than what we did
in the first program.
The program operates in exactly the same manner as the first program
example. This should not be surprising because a pointer to a method can
be used to operate on an object in the same manner as an object can be
directly manipulated.

17.5

Be sure to compile and run this program before continuing on to the next
program example. In this program you will notice that we failed to check
the allocation to see that it did allocate the objects properly or not, and we
also failed to de-allocate the objects prior to terminating the program.
In such a simple program, it doesn't matter because the heap will be
cleaned up automatically when we return to the operating system.
In real program development you have to implement this allocation
checking and the de-allocation. As shown in the previous Module, if we
do not de-allocate, there will be garbage left.
A Pointer And A Virtual Function
The program example named poly4.cpp is identical to the last program
except for the addition of the keyword virtual to line 12 once again.
1. // program poly4.cpp
2. #include <iostream>
3. using namespace std;
4.
5. // a base class declaration
6. // and the implementation part
7. class vehicle
8. {
9.
int wheels;
10.
float weight;
11.
public:
12.
virtual void message(void)
13.
// first message(), with virtual keyword
14.
{cout<<"Vehicle message, from vehicle, the base class\n";}
15. };
16.
17. // a derived class declaration and implementation part
18. class car : public vehicle
19. {
20.
int passenger_load;
21.
public:
22.
void message(void) // second message()
23.
{cout<<"Car message, from car, the vehicle derived
class\n";}
24. };
25.
26. class truck : public vehicle
27. {
28.
int passenger_load;
29.
float payload;
30.
public:
31.
int passengers(void) {return passenger_load;}
32. };
33.

34. class boat : public vehicle


35. {
36.
int passenger_load;
37.
public:
38.
int passengers(void) {return passenger_load;}
39.
void message(void) // third message()
40.
{cout<<"Boat message, from boat, the vehicle derived
class\n";}
41. };
42.
43. // the main program
44. int main()
45. {
46.
vehicle *unicycle;
47.
car *sedan_car;
48.
truck *trailer;
49.
boat *sailboat;
50.
51.
cout<<"Re add the virtual keyword. Using\n";
52.
cout<<"pointer variables, and new keyword\n";
53.
cout<<"-----------------------------------\n";
54.
55.
unicycle = new vehicle;
56.
unicycle->message();
57.
sedan_car = new car;
58.
sedan_car->message();
59.
trailer = new truck;
60.
trailer->message();
61.
sailboat = new boat;
62.
sailboat->message();
63.
64.
unicycle = sedan_car;
65.
unicycle->message();
66.
67.
// system("pause");
68.
return 0;
69. }
69 Lines: Output:

17.6

By including the keyword virtual, it is still identical to the last program.


Once again we are simply using pointers to each of the objects, and in
every case the pointer is of the same type as the object to which it points.
You will begin to see some changes in the next program example.
Please compile and run this program. The four previous programs were
meant just to show to you in what virtual functions do not do. The next two
will show you what virtual functions do.
A Single Pointer To The Parent Class
Examine the program example named poly5.cpp where we almost use a
virtual function. We are almost ready to use a virtual method.
1. // program poly5.cpp
2. #include <iostream>
3. using namespace std;
4.
5. // a base class declaration
6. // and the implementation part
7. class vehicle
8. {
9.
int wheels;
10.
float weight;
11.
public:
12.
void message(void)
13.
// first message()
14.
{cout<<"Vehicle message, from vehicle, the base class\n";}
15. };
16.
17. // a derived class declaration and implementation part
18. class car : public vehicle
19. {
20.
int passenger_load;
21.
public:
22.
void message(void) // second message()
23.
{cout<<"Car message, from car, the vehicle derived
class\n";}
24. };
25.
26. class truck : public vehicle

27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.

{
int passenger_load;
float payload;
public:
int passengers(void) {return passenger_load;}
};

class boat : public vehicle


{
int passenger_load;
public:
int passengers(void) {return passenger_load;}
void message(void) // third message()
{cout<<"Boat message, from boat, the vehicle derived
class\n";}
41. };
42.
43. // the main program
44. int main()
45. {
46.
47.
cout<<"Omitting the virtual keyword. Using\n";
48.
cout<<"pointer variables, new and\n";
49.
cout<<"delete keyword\n";
50.
cout<<"-----------------------------------\n";
51.
52.
vehicle *unicycle;
53.
unicycle = new vehicle;
54.
unicycle->message();
55.
delete unicycle;
56.
57.
unicycle = new car;
58.
unicycle->message();
59.
delete unicycle;
60.
61. unicycle = new truck;
62. unicycle->message();
63.
delete unicycle;
64.
65. unicycle = new boat;
66. unicycle->message();
67.
delete unicycle;
68.
69.
// unicycle = sedan_car;
70.
// unicycle->message();
71.

72. // system("pause");
73. return 0;
74. }
74 Lines: Output:

The keyword virtual omitted again in line 12 and with a totally different
main() program. In this program, we only define a single pointer to a class
and the pointer is pointing to the base class of the class hierarchy. We will
use the single pointer to refer to each of the four classes and observe
what the output of the method named message() is.
If we referred to a vehicle (in the real world, not necessarily in this
program), we could be referring to a car, a truck, a motorcycle, or any
other kinds of transportation, because we are referring to a very general
form of an object.
If however, we were to refer to a car, we are excluding trucks,
motorcycles, and all other kinds of transportation, because we are
referring to a car specifically. The more general term of vehicle can
therefore refer to a many kinds of vehicles, but the more specific term of
car can only refer to a single kind of vehicle, namely a car.
We can apply the same thought process in C++ and say that if we have a
pointer to a vehicle, we can use that pointer to refer to any of the more
specific objects whereas if we have a pointer to a car, we cannot use that
pointer to reference any of the other classes including the vehicle class
because the pointer to the car class is too specific and restricted to be
used on any other classes.

C++ Polymorphism and Abstract Base Class


Before you start reading this C++ tutorial on polymorphism you should have a good
understanding of class inheritance and pointers.

Introduction to Polymorphism
Polymorphism is by far the most important and widely used concept in object oriented
programming. Some of the widely used technologies and libraries like COM, MFC etc.
have polymorphism as their foundation. If you look at all the original design patterns,
almost every pattern uses polymorphism in its structure.
Polymorphism is a mechanism that allows you to implement a function in different ways.

Pointers to base class


We have seen that it is possible to derive a class from a base class and that we can add
functionality to member functions.
One of the features of derived classes is that a pointer to a derived class is typecompatible with a pointer to its base class. Polymorphism takes advantage of this feature.
Lets take a look at an example of a base class and derived classes:
#include <iostream>
using namespace std;
class CPolygon
{
protected:
int width, height;
public:
void setup (int first, int second)
{
width= first;
height= second;
}
};
class CRectangle: public CPolygon
{
public:
int area()
{
return (width * height);
}
};
class CTriangle: public CPolygon

public:
int area()
{
return (width * height / 2);
}

};
int main ()
{
CRectangle rectangle;
CTriangle triangle;
CPolygon * ptr_polygon1 = &rectangle;
CPolygon * ptr_polygon2 = &triangle;
ptr_polygon1->setup(2,2);
ptr_polygon2->setup(2,2);
cout << rectangle.area () << endl;
cout << triangle.area () << endl;
}

return 0;

As you can see, we create two pointers (ptr_polygon1 and ptr_polygon2) that point to the
objects of class CPolygon. Then we assign to these pointers the address of (using the
reference ampersand sign) the objects rectangle and triangle. Both rectangle and triangle
are objects of classes derived from CPolygon.
In the cout statement we use the objects rectangle and triangle instead of the pointers
ptr_polygon1 and ptr_polygon2. We do this because ptr_polygon1 and ptr_polygon2 are
of the type CPolygon. This means we can only use the pointers to refer to members that
CRectangle and CTriangle inherit from Cpolygon.
If we want to use the pointers to class CPolygon then area() should be declared in the
class CPolygon and not only in the derived classes CRectangle and Ctriangle.
The problem is that we use different versions of area() in the derived classes
CRectangle and Ctriangle so we cant implement one version of area() in the base class
CPolygon. (If they were the same we had no problem.)
We can fix this by using virtual members.

Virtual Members
A virtual member is a member of a base class that we can redefine in its derived classes.
To declare a member as virtual we must use the keyword virtual.
Lets change our previous example:

#include <iostream>
using namespace std;
class CPolygon
{
protected:
int width, height;
public:
void setup (int first, int second)
{
width= first;
height= second;
}
virtual int area()
{
return (0);
}
};
class CRectangle: public CPolygon
{
public:
int area()
{
return (width * height);
}
};
class CTriangle: public CPolygon
{
public:
int area()
{
return (width * height / 2);
}
};
int main ()
{
CRectangle rectangle;
CTriangle triangle;
CPolygon polygon;
CPolygon * ptr_polygon1 = &rectangle;
CPolygon * ptr_polygon2 = &triangle;
CPolygon * ptr_polygon3 = &polygon;
ptr_polygon1->setup(2,2);
ptr_polygon2->setup(2,2);
ptr_polygon3->setup(2,2);
cout << ptr_polygon1->area () << endl;
cout << ptr_polygon2->area () << endl;
cout << ptr_polygon3->area () << endl;
return 0;

Because of the change adding area() as a virtual member of CPolygon now all the
three classes have all the same members (width, height, setup() and area().)
A class that declares or inherits a virtual function is called a polymorphic class.

Abstract Base Classes (ABC)


At the design level, an abstract base class (ABC) corresponds to an abstract concept. For
instance: if you ask to draw a shape, I will probably ask what kind of shape. The term
shape is an abstract concept, it could be a circle, a square, etc, etc. You could say in C+
+ that class CShape is an abstract base class (ABC) and class circle (etc) could be a
derived class.
As we look at the C++ language we could say that an abstract base class has one or more
pure virtual member functions.
In the example above we put an implementation (return (0);) in the virtual member
function area(). If we want to change it into a pure virtual member function we use =0;
instead of the return (0). So the class will look like this:
class CPolygon
{
protected:
int width, height;
public:
void setup (int first, int second)
{
width= first;
height= second;
}
virtual int area() = 0;
};

This pure virtual function area() makes CPolygon an abstract base class. But you have to
remember the following: by adding a pure virtual member to the base class, you are
forced to also add the member to any derived class.
So our example should now look like this:
#include <iostream>
using namespace std;
class CPolygon
{

};

protected:
int width, height;
public:
void setup (int first, int second)
{
width= first;
height= second;
}
virtual int area() = 0;

class CRectangle: public CPolygon


{
public:
int area(void)
{
return (width * height);
}
};
class CTriangle: public CPolygon
{
public:
int area(void)
{
return (width * height / 2);
}
};
int main ()
{
CRectangle rectangle;
CTriangle triangle;
CPolygon * ptr_polygon1 = &rectangle;
CPolygon * ptr_polygon2 = &triangle;
ptr_polygon1->setup(2,2);
ptr_polygon2->setup(2,2);
cout << ptr_polygon1->area () << endl;
cout << ptr_polygon2->area () << endl;
return 0;
}

Note: there is also an extra void in the derived classes CRectangle and CTriangle.
Using a unique type of pointer (CPolygon*) we can point to objects of different but
related classes.
We can make use of that. For instance: we could implement an extra function member in
the abstract base class CPolygon that can print the result of the area() function.
(Remember that CPolygon itself has no implementation for the function area() and still

we can use it, isnt it cool.) After implementation of such a function the example will
look like this:
#include <iostream>
using namespace std;
class CPolygon
{
protected:
int width, height;
public:
void setup (int first, int second)
{
width= first;
height= second;
}
virtual int area(void) = 0;
void onscreen(void)
{
cout << this->area() << endl;
}
};
class CRectangle: public CPolygon
{
public:
int area(void)
{
return (width * height);
}
};
class CTriangle: public CPolygon
{
public:
int area(void)
{
return (width * height / 2);
}
};
int main ()
{
CRectangle rectangle;
CTriangle triangle;
CPolygon * ptr_polygon1 = &rectangle;
CPolygon * ptr_polygon2 = &triangle;
ptr_polygon1->setup(2,2);
ptr_polygon2->setup(2,2);
ptr_polygon1->onscreen();
ptr_polygon2->onscreen();

return 0;

As you can see this can be very useful.

Dynamic Allocation
In an earlier tutorial we already looked at dynamic allocation using the new operator.
(So we dont have to explain that again). In this last section we will change the previous
example and we will dynamically allocate the objects.
Take a look at the next example:
#include <iostream>
using namespace std;
class CPolygon
{
protected:
int width, height;
public:
void setup (int first, int second)
{
width= first;
height= second;
}
virtual int area(void) = 0;
void onscreen(void)
{
cout << this->area() << endl;
}
};
class CRectangle: public CPolygon
{
public:
int area(void)
{
return (width * height);
}
};
class CTriangle: public CPolygon
{
public:
int area(void)
{
return (width * height / 2);
}
};
int main ()

CPolygon * ptr_polygon1 = new CRectangle;


CPolygon * ptr_polygon2 = new CTriangle;
ptr_polygon1->setup(2,2);
ptr_polygon2->setup(2,2);
ptr_polygon1->onscreen();
ptr_polygon2->onscreen();
delete ptr_polygon1;
delete ptr_polygon2;
return 0;

That is all for this tutorial.

Interfaces in C++ (Abstract Classes)


Advertisements
Previous Page
Next Page
An interface describes the behavior or capabilities of a C++ class without committing to a
particular implementation of that class.
The C++ interfaces are implemented using abstract classes and these abstract classes
should not be confused with data abstraction which is a concept of keeping
implementation details separate from associated data.
A class is made abstract by declaring at least one of its functions as pure virtual
function. A pure virtual function is specified by placing "= 0" in its declaration as
follows:
class Box
{
public:
// pure virtual function
virtual double getVolume() = 0;
private:

};

double length;
double breadth;
double height;

// Length of a box
// Breadth of a box
// Height of a box

The purpose of an abstract class (often referred to as an ABC) is to provide an


appropriate base class from which other classes can inherit. Abstract classes cannot be
used to instantiate objects and serves only as an interface. Attempting to instantiate an
object of an abstract class causes a compilation error.
Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the
virtual functions, which means that it supports the interface declared by the ABC. Failure
to override a pure virtual function in a derived class, then attempting to instantiate objects
of that class, is a compilation error.
Classes that can be used to instantiate objects are called concrete classes.

Abstract Class Example:


Consider the following example where parent class provides an interface to the base class
to implement a function called getArea():
#include <iostream>
using namespace std;
// Base class
class Shape
{
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived classes
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);

}
};
class Triangle: public Shape
{
public:
int getArea()
{
return (width * height)/2;
}
};
int main(void)
{
Rectangle Rect;
Triangle Tri;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;
Tri.setWidth(5);
Tri.setHeight(7);
// Print the area of the object.
cout << "Total Triangle area: " << Tri.getArea() << endl;
}

return 0;

When the above code is compiled and executed, it produces the following result:
Total Rectangle area: 35
Total Triangle area: 17

You can see how an abstract class defined an interface in terms of getArea() and two
other classes implemented same function but with different algorithm to calculate the
area specific to the shape.

Designing Strategy:
An object-oriented system might use an abstract base class to provide a common and
standardized interface appropriate for all the external applications. Then, through
inheritance from that abstract base class, derived classes are formed that all operate
similarly.
The capabilities (i.e., the public functions) offered by the external applications are
provided as pure virtual functions in the abstract base class. The implementations of these
pure virtual functions are provided in the derived classes that correspond to the specific
types of the application.
This architecture also allows new applications to be added to a system easily, even after
the system has been defined.

Quarter-finals:
Wed 18 March QF3 - Sri Lanka (A3) v South Africa (B2), Sydney Cricket Ground
(SCG)
Thu 19 March QF4 - Bangladesh (A4) v India (B1), Melbourne Cricket Ground (MCG)
Fri 20 March QF2 - Australia (A2) v Pakistan (B3), Adelaide Oval
Sat 21 March QF1 - New Zealand (A1) v West Indies (B4), Wellington Regional
Stadium
Semi-finals:
Tue 24 March SF1 - Winner QF1 (NZ v WI) v Winner QF3 (SL v SA), Eden Park,
Auckland
Thu 26 March SF2 - Winner QF2 (Aus v Pak) v Winner QF4 (BD v Ind), SCG, Sydney
Final:
Sun 29 March Melbourne Cricket Ground

You might also like