Data Types Operators
Data Types Operators
Data Types Operators
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;
}
#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
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
If-then-else Statements 2
Switch Statements 2
For Loops 2
While Loops 2
Break and Continue 2
Goto & Labels 2
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
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
Float Datatype 2
Sizeof 2
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
$
#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;
#include <stdio.h>
int main()
{
int main = 3;
printf("%d", main);
return 0;
}
$ 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;
}
Answer: a
Explanation:volatile is C keyword.
#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");
}
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.
#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
#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;
}
#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.
#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
#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
#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
#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
#include <stdio.h>
int const print()
{
printf("Sanfoundry.com");
return 0;
}
void main()
{
print();
}
#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;
}
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;
}
#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;
#include <stdio.h>
void main()
{
int k = 4;
float k = 4;
printf("%d", k)
}
$ 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.
#include <stdio.h>
int main()
{
int i = -3;
int k = i % 2;
printf("%d\n", k);
}
#include <stdio.h>
int main()
{
int i = 3;
int l = i / -2;
int k = i % -2;
printf("%d %d\n", l, k);
return 0;
}
#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
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
#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
#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
;
}
#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
#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
#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);
}
#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
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);
}
#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
#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");
}
#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;
}
#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
#include <stdio.h>
void main()
{
int x = 0;
if (x = 0)
printf("Its zero\n");
else
printf("Its not zero\n");
}
#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
#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);
}
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);
}
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
#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);
}
#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.
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);
}
#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
#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) returns 1
b) returns 2
c) Varies
#include <stdio.h>
void main()
{
1 < 2 ? return 1 : return 2;
}
#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);
}
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
#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;
#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++;
}
#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);
}
#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);
}
#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
#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
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
End Function
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)
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) { }
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 = ▭
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); }
};
int main () {
Rectangle rect;
Triangle trgl;
Polygon poly;
Polygon * ppoly1 = ▭
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
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;
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;
20
10
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
20
10
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
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;
}
are declared being of type "pointer to Polygon", but the objects allocated have been
declared having the derived class type directly (Rectangle and Triangle).
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;
};
Output:
fun() called
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()
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()
Output:
x = 4, y = 5
{
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
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
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
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
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.
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.
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.
17.6
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;}
};
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.
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.
public:
int area()
{
return (width * height / 2);
}
};
int main ()
{
CRectangle rectangle;
CTriangle triangle;
CPolygon * ptr_polygon1 = &rectangle;
CPolygon * ptr_polygon2 = ▵
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 = ▵
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.
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;
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 = ▵
ptr_polygon1->setup(2,2);
ptr_polygon2->setup(2,2);
ptr_polygon1->onscreen();
ptr_polygon2->onscreen();
return 0;
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 ()
};
double length;
double breadth;
double height;
// Length of a box
// Breadth of a box
// Height of a box
}
};
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