Skip to main content

Nepal Engineering Council · Chapter 3

Programming Language and Its Applications

Pick an answer for each question, then open “Show answer” to check it.

504 questions in 6 syllabus topics · 28 tagged from past exams or NEC model sets.

3.1 Introduction to C programming

110 questions · ACtE0301

1. What is the purpose of a semicolon in C programming?

Aasadh 2081 exam
  1. Option A: Indicate end of statement
  2. Option B: Separate two statements
  3. Option C: Define function
  4. Option D: Declare variable
Show hint

Semicolon marks the end of an instruction.

Show answer

Answer: A. Indicate end of statement

Semicolon (;) indicates the end of a C statement and is required for statement termination.

2. What is C++ for loop correct syntax?

Aasadh 2081 exam
  1. Option A: for (initialization; condition; increment/decrement)
  2. Option B: for (condition; initialization; increment/decrement)
  3. Option C: for (increment; condition; initialization)
  4. Option D: for (condition; increment; initialization)
Show hint

Init-Cond-Update order.

Show answer

Answer: A. for (initialization; condition; increment/decrement)

Correct C++ for loop syntax: for (initialization; condition; increment/decrement) { statements }

3. What is the correct syntax for declaring a function in C?

  1. Option A: type_of_return name_of_function (argument type);
  2. Option B: type_of_return name_of_function (argument type){}
  3. Option C: type_of_return (argument type) name_of_function;
  4. Option D: All of the above
Show hint

Function declarations end with semicolon in C.

Show answer

Answer: A. type_of_return name_of_function (argument type);

Correct C function declaration syntax: return_type function_name(parameter_types); The declaration specifies what the function does without implementing it.

4. Which of the following is NOT a C format specifier?

  1. Option A: %d
  2. Option B: %f
  3. Option C: %s
  4. Option D: %t
Show hint

Valid specifiers: %d, %f, %s, %c. What's missing?

Show answer

Answer: D. %t

%t is not a standard C format specifier. Valid specifiers include %d (int), %f (float), %s (string), %c (char), %x (hex), %o (octal).

5. What is compiler vs interpreter difference?

  1. Option A: Compiler line-by-line, interpreter all at once
  2. Option B: Compiler all at once, interpreter line-by-line
  3. Option C: Both translate all
  4. Option D: Both translate line-by-line
Show hint

Timing of translation differs.

Show answer

Answer: B. Compiler all at once, interpreter line-by-line

Compiler translates entire program before execution. Interpreter translates and executes line by line during runtime.

6. What are C Tokens?

  1. Option A: Keywords and identifiers only
  2. Option B: Smallest individual units of a C program
  3. Option C: Comments in the code
  4. Option D: Memory allocation units
Show hint

C tokens are the building blocks of source code - think of what compiler recognizes.

Show answer

Answer: B. Smallest individual units of a C program

C Tokens are the smallest individual units of a C program that the compiler recognizes. They include keywords (like int, void, return), identifiers (variable names), constants (literal values like 5, 3.14, 'a'), strings ("hello"), operators (+, -, *, /), and special symbols ({}, [], ()). Every valid C program is a sequence of tokens separated by whitespace. For example, in 'int x = 5;', the tokens are: int, x, =, 5, and ;. Tokens cannot be broken down further without losing meaning. Understanding tokens is fundamental because the lexical analyzer (first phase of compilation) converts source code into a token stream, which the parser then uses to build the syntax tree.

7. Which of the following is NOT a C token?

  1. Option A: int x;
  2. Option B: int
  3. Option C: x
  4. Option D: ;
Show hint

Tokens are individual units, not complete statements.

Show answer

Answer: A. int x;

'int x;' is a complete statement consisting of multiple tokens: 'int' (keyword token), 'x' (identifier token), and ';' (special symbol token). A statement is a sequence of tokens, not a single token. Each component 'int', 'x', and ';' individually are tokens. This distinction is crucial in understanding how compilers parse code - they first break code into tokens, then analyze token sequences to understand program structure. The semicolon marks statement termination and is itself a token.

8. What are the main categories of C operators?

  1. Option A: Arithmetic and logical only
  2. Option B: Arithmetic, logical, relational, assignment, bitwise, and special operators
  3. Option C: Mathematical operations only
  4. Option D: Comparison operators only
Show hint

Consider operators like +, &&, ==, =, &, and others like sizeof.

Show answer

Answer: B. Arithmetic, logical, relational, assignment, bitwise, and special operators

C supports multiple operator categories: (1) Arithmetic operators (+, -, *, /, %) for mathematical operations; (2) Relational operators (==, !=, <, >, <=, >=) for comparison returning boolean values; (3) Logical operators (&&, ||, !) for boolean logic; (4) Assignment operators (=, +=, -=, *=, /=, %=, etc.) for variable assignment; (5) Bitwise operators (&, |, ^, ~, <<, >>) for bit-level operations; (6) Special operators like sizeof (memory size), & (address), * (pointer dereference), ?: (ternary), and comma. Operator precedence and associativity determine evaluation order - for example, * and / have higher precedence than + and -. Understanding all operator categories is essential for writing correct expressions and avoiding logical errors.

9. What is the purpose of formatted input in C?

  1. Option A: To convert data into specific formats
  2. Option B: To read input data according to specified format specifications
  3. Option C: To align output on screen
  4. Option D: To encrypt user data
Show hint

Think about scanf() and how %d, %f, %s work.

Show answer

Answer: B. To read input data according to specified format specifications

Formatted input in C uses functions like scanf() and fscanf() to read data from standard input or files according to format specifications. Format specifiers (%d for integer, %f for float, %s for string, %c for character, %x for hexadecimal, %o for octal) tell the function what type of data to expect and how to interpret the input stream. For example, scanf("%d %f %s", &integer, &floating, string) expects an integer, then a float, then a string from input. This allows reading mixed data types in a structured manner. The advantage is flexibility in input handling, but disadvantages include complexity and potential buffer overflow risks with %s. Format specifications also include width and precision modifiers like %5d (read 5 characters) or %.2f (2 decimal places). Proper format specification matching with variable types is critical to prevent undefined behavior.

10. What does unformatted input in C do?

  1. Option A: Reads data without format specifications
  2. Option B: Reads data character by character or in raw form
  3. Option C: Converts input to specific data types automatically
  4. Option D: Encrypts incoming data
Show hint

Functions like getchar(), gets(), and fgets() are unformatted.

Show answer

Answer: B. Reads data character by character or in raw form

Unformatted input in C reads data without requiring format specifications, processing input as-is. Functions include getchar() (reads single character), getche() (reads character with echo), getch() (reads character without echo), gets() (reads entire line - UNSAFE, causes buffer overflow), and fgets() (safe alternative to gets(), reads line with specified size limit). Unformatted input is simpler and faster than formatted input but lacks automatic type conversion. For example, getchar() returns an int (ASCII value) of the character read, or EOF (-1) on end-of-file. This approach is useful when you want to process data character-by-character or handle raw input. Important: gets() is deprecated and removed from modern C standards due to security risks; fgets() is preferred as it allows specifying maximum characters to read. Unformatted functions are also useful in interactive programs where you want immediate character processing.

11. What is the difference between if-else and switch control statements?

  1. Option A: No significant difference
  2. Option B: if-else handles ranges, switch handles exact values
  3. Option C: switch is faster than if-else
  4. Option D: if-else can check multiple conditions, switch checks single variable
Show hint

Consider what each statement is best used for - flexibility vs. simplicity.

Show answer

Answer: D. if-else can check multiple conditions, switch checks single variable

if-else and switch are both control statements but serve different purposes: if-else allows checking multiple independent conditions with boolean expressions (if x > 10 && y < 5), handles ranges, and uses comparison operators. switch evaluates a single expression and compares it against multiple constant cases, executing matching case block. switch is more efficient when checking one variable against many discrete values, as it may use jump tables. However, if-else is more flexible for complex conditions. Example: switch (day) {case 1: ...; break; case 2: ...} vs if (day==1) {...} else if (day==2) {...}. switch requires break statements to prevent fall-through (executing subsequent cases). switch cases must be constants, while if-else conditions can be complex expressions. For simple discrete value comparisons, switch is preferred; for range checks or multiple condition logic, if-else is necessary. The default case in switch is like final else in if-else chain.

12. What are the types of loops in C?

  1. Option A: for and while only
  2. Option B: for, while, and do-while
  3. Option C: for and do-while only
  4. Option D: while and nested loops only
Show hint

How many different loop constructs does C provide?

Show answer

Answer: B. for, while, and do-while

C provides three types of loops: (1) while loop: checks condition before each iteration, may not execute at all if condition is false initially. Syntax: while(condition) { statements }. Best for unknown iteration count. (2) do-while loop: executes body first, then checks condition, guaranteeing at least one execution. Syntax: do { statements } while(condition). Best for input validation where you must process at least once. (3) for loop: most compact, combines initialization, condition, and increment. Syntax: for(init; condition; increment) { statements }. Best for known iteration count. Additionally, C supports nested loops (loop inside another loop), break statement (exits current loop), continue statement (skips current iteration), and goto statement (though discouraged). Understanding loop selection is crucial: for loops suit array iterations, while loops suit event-driven processing, and do-while suits menu systems. Loop control variables should be carefully managed to prevent infinite loops.

13. What is function prototyping in C?

  1. Option A: Creating sample functions
  2. Option B: Declaring function signature before definition
  3. Option C: Testing functions before use
  4. Option D: Copying function implementations
Show hint

Why do we write function declarations at the top of files?

Show answer

Answer: B. Declaring function signature before definition

Function prototyping is declaring a function's signature (return type, name, and parameters) before its implementation. Syntax: return_type function_name(parameter_types); without the body. Prototypes allow forward declaration, enabling the compiler to verify function calls before seeing the actual implementation. Benefits: (1) Type checking - compiler ensures calls match declaration; (2) Organization - main() can call functions defined later; (3) Compilation - prevents 'function undeclared' errors; (4) Readability - clearly documents function interfaces. Example: int add(int a, int b); before int add(int a, int b) { return a+b; }. Prototypes are typically placed in header files or at file top. Parameters can be empty () or specified with types. Parameter names in prototypes are optional: int add(int, int) is valid. This is different from function definition which includes the implementation body. Modern C standards (C99, C11) recommend explicit prototyping of all functions.

14. What is a recursive function?

  1. Option A: Function that calls itself directly or indirectly
  2. Option B: Function that repeats in a loop
  3. Option C: Function that calls another function multiple times
  4. Option D: Function with repeated code
Show hint

Think of factorial or Fibonacci calculations.

Show answer

Answer: A. Function that calls itself directly or indirectly

A recursive function is one that calls itself (direct recursion) or calls another function that eventually calls back to it (indirect recursion). Every recursive function needs: (1) Base case - condition that stops recursion to prevent infinite loops; (2) Recursive case - call with simplified/modified parameters approaching base case; (3) Progress toward base case. Example: factorial(n) = n * factorial(n-1) with base case factorial(0) = 1. Recursion uses the call stack, storing return addresses and local variables. Each recursive call creates new stack frame. Disadvantages: stack overflow risk, slower than iteration, higher memory usage. Advantages: elegant solution for inherently recursive problems (trees, divide-and-conquer), cleaner code. Tail recursion (recursive call is last operation) can be optimized by compilers. Common recursive problems: factorial, Fibonacci, tree traversal, permutations, binary search. Understanding stack depth is crucial - deep recursion can exhaust stack memory. Iterative solutions are often more efficient than recursive ones, but recursion provides conceptual clarity for certain algorithms.

15. What are one-dimensional arrays in C?

  1. Option A: Arrays with one row and multiple columns
  2. Option B: Linear collection of elements of same type with single index
  3. Option C: Arrays with only one element
  4. Option D: Arrays stored in one memory location
Show hint

Think of a simple list or vector accessed by single index.

Show answer

Answer: B. Linear collection of elements of same type with single index

One-dimensional (1D) arrays are linear collections of elements of the same data type accessed using a single index. Declaration: type array_name[size]; Example: int arr[5]; creates integer array for 5 elements indexed 0-4. Memory allocation: contiguous block of (size * sizeof(type)) bytes. Initialization: int arr[] = {1,2,3,4,5} or int arr[5] = {0}. Accessing: arr[i] retrieves i-th element. Array operations: traversal (loop through all), search (find element), sorting, mathematical operations. Passing arrays to functions: decays to pointer (int* arr), so array modifications affect original. Advantages: random access (O(1)), cache-friendly, simple. Disadvantages: fixed size (in C, dynamic allocation needed for variable size), requires bounds checking to prevent overflow. String arrays: char str[50] stores null-terminated strings. Multi-dimensional arrays are treated as arrays of arrays. Important: array indices are 0-based; arr[5] in size-5 array is undefined (out of bounds). Arrays form foundation for data structures like queues, stacks, and heaps.

16. What is a two-dimensional array in C?

  1. Option A: Array with rows and columns like a matrix
  2. Option B: Array containing two elements
  3. Option C: Array with two types of data
  4. Option D: Array accessed with two operations
Show hint

Think of a spreadsheet or matrix structure.

Show answer

Answer: A. Array with rows and columns like a matrix

Two-dimensional (2D) arrays are tables with rows and columns, representing matrices. Declaration: type array[rows][cols]; Example: int matrix[3][4] creates 3x4 integer matrix. Memory layout: stored row-major order in C - all of row 0, then row 1, etc. Access: matrix[i][j] accesses element at row i, column j. Initialization: int matrix[2][3] = {{1,2,3},{4,5,6}}; Total size: 3*4*sizeof(int) bytes contiguous. Passing to functions: void func(int arr[][4]) - second dimension must be specified because compiler calculates stride. Nested loops for traversal: for(i=0;i<rows;i++) for(j=0;j<cols;j++) process matrix[i][j]. Applications: image processing (pixels), game boards, spreadsheets, mathematical matrices. Alternative: array of pointers (int *arr[3]) creates jagged array with flexible row sizes. Multidimensional arrays generalize to 3D, 4D, etc., but overhead increases. Memory is still contiguous in C, unlike some languages. Index bounds checking is programmer's responsibility - out-of-bounds access is undefined behavior. Understanding memory layout is crucial for passing to functions and pointer arithmetic.

17. What is string manipulation in C?

  1. Option A: Changing integers to strings
  2. Option B: Operations on character arrays terminated by null character
  3. Option C: Removing special characters from strings
  4. Option D: Converting strings to uppercase
Show hint

Strings in C are char arrays ending with '\0'. Consider operations like strlen, strcpy, etc.

Show answer

Answer: B. Operations on character arrays terminated by null character

String manipulation involves operations on null-terminated character arrays. Strings in C: char str[20] = "hello" stores h,e,l,l,o,\0 (null terminator marks end). Key operations: strlen(str) returns string length excluding null. strcpy(dest, src) copies string src to dest (unsafe, no bounds check). strncpy(dest, src, n) copies max n characters (safer). strcat(dest, src) concatenates src to dest. strncat(dest, src, n) concatenates max n characters. strcmp(str1, str2) compares strings, returns 0 if equal. strchr(str, c) finds character c in string. strstr(str1, str2) finds substring str2 in str1. sprintf(buffer, format, ...) formats string into buffer. String operations require string.h header. Common pitfalls: buffer overflow with strcpy (use strncpy), forgetting null terminator, comparing pointers instead of content with ==. Modern approach: use safer functions with size limits. Strings are immutable in sense that operations create new copies or modify arrays. Understanding null-termination is crucial - forgetting it causes undefined behavior. String functions are fundamental for text processing, parsing input, and data manipulation.

18. What is multidimensional array in C?

  1. Option A: Arrays with more than two dimensions
  2. Option B: Three-dimensional arrays only
  3. Option C: Arrays with varying dimensions
  4. Option D: Arrays stored in multiple memory locations
Show hint

Generalization of 2D arrays to 3D, 4D, and beyond.

Show answer

Answer: A. Arrays with more than two dimensions

Multidimensional arrays extend beyond 2D to any number of dimensions. Declaration: type array[d1][d2][d3]...[dn]; Example: int cube[3][3][3] creates 3x3x3 array (27 elements). Memory: allocated contiguously in row-major order. Access: cube[i][j][k] accesses element using all indices. Storage: total size = d1*d2*d3*...*dn*sizeof(type). Initialization: int cube[2][2][2] = {{{1,2},{3,4}},{{5,6},{7,8}}}; Traversal: nested loops for each dimension. Practical applications: 3D graphics (x,y,z coordinates), 3D grids (physics simulations), time-series data (3D with time dimension), image stacks. Passing to functions requires specifying all but first dimension: void func(int arr[][3][3]) for 3D array. Memory layout understanding critical - for cube[i][j][k], memory position calculated as: base + ((i*d2*d3 + j*d3 + k)*sizeof(type)). Performance: cache efficiency decreases with dimensions due to fewer elements per cache line. Pointers of pointers alternative: int ***arr for dynamic allocation but more complex. Higher dimensions increase complexity significantly; careful memory management essential.

19. What does printf() do in C?

  1. Option A: Reads formatted input from keyboard
  2. Option B: Writes formatted output to stdout
  3. Option C: Declares print format
  4. Option D: Prints only integers
Show hint

Formatted output function - think of how you display variables.

Show answer

Answer: B. Writes formatted output to stdout

printf() writes formatted output to standard output (stdout). Syntax: printf(format_string, arguments); Format specifiers: %d (int), %f (float), %lf (double), %c (char), %s (string), %x (hex), %o (octal), %p (pointer). Modifiers: %5d (width 5), %.2f (2 decimal places), %-5d (left-aligned), %05d (zero-padded). Example: printf("Value: %d, Name: %s\n", 42, "test") outputs formatted text with values. Return value: number of characters printed (or negative on error). Escape sequences: \n (newline), \t (tab), \" (quote), \\ (backslash). Printf advantage: single function for multiple data types. Disadvantages: no type checking (dangerous), complex format strings, slower than direct output. Variants: fprintf(FILE*, format, args) writes to file; sprintf(buffer, format, args) writes to string buffer; snprintf(buffer, size, format, args) with size limit (safer). Format string vulnerabilities: untrusted format strings cause security issues. Understanding format specifiers crucial - %d for pointer using %p, mismatches cause undefined behavior. Printf is fundamental for debugging and user interaction, but modern C developers prefer snprintf for safety.

20. What is the difference between formatted and unformatted output in C?

  1. Option A: No significant difference
  2. Option B: Formatted specifies output format, unformatted outputs as-is
  3. Option C: Formatted is for strings, unformatted for numbers
  4. Option D: Formatted is slower than unformatted
Show hint

Compare printf with putchar or puts.

Show answer

Answer: B. Formatted specifies output format, unformatted outputs as-is

Formatted output uses format specifiers to control output appearance: printf("%5d %.2f", x, y) - explicit format. Unformatted output displays data as-is without specification: putchar(c) outputs character, puts(str) outputs string with newline, putch(c) with echo. Key differences: Formatted: requires format string with specifiers (%d, %f, %s, etc.), supports width/precision, allows multiple arguments, slower due to parsing, risk of format vulnerabilities. Unformatted: simple character/string output, faster (direct write), no format parsing, suitable for raw output. Examples: printf("Number: %d", 42) vs putchar('x'). Use formatted for structured output (reports, formatted tables, numbers with specific precision). Use unformatted for simple character I/O, interactive menus, raw data output. Unformatted functions: putchar() (single char), putch() (char with echo), puts() (string + newline), fputc() (to file), fputs() (string to file). Modern practice: printf/fprintf/sprintf family dominates due to flexibility. Buffer flushing: fflush(stdout) ensures output appears immediately. Understanding performance difference matters for high-frequency output scenarios.

21. What are user-defined functions in C?

  1. Option A: Functions provided by standard library
  2. Option B: Functions written by programmer for specific tasks
  3. Option C: Functions with user input parameters
  4. Option D: Functions that modify user data
Show hint

Functions you write yourself, not from library.

Show answer

Answer: B. Functions written by programmer for specific tasks

User-defined functions are functions written by programmers to perform specific tasks, promoting code reusability and modularity. Structure: return_type function_name(parameters) { function body; return value; }. Example: int add(int a, int b) { return a + b; }. Benefits: code reuse, modularity, easier debugging, improved readability, maintainability. Function components: (1) Function signature: defines interface. (2) Function body: implementation. (3) Return statement: sends value back to caller. (4) Parameters: input values. Scope rules: local variables exist within function, global variables accessible from anywhere. Parameter passing: pass-by-value (copy of value), pass-by-pointer (address, allows modification). Return types: void (no return), int, float, pointer, struct, array (as pointer). Recursion: function calling itself. Function pointers: void (*funcPtr)(int); pointing to functions. Benefits for larger programs: divide complex logic into manageable pieces, enable team development (different team members write functions), facilitate testing. Organization: function declaration (prototype), then main(), then function definitions. Many programmers place function definitions before main() to avoid forward declarations. Understanding scope, parameter passing, and return values essential for effective function use.

22. Which of the following is not a data type in C?

NEC model set
  1. Option A: int
  2. Option B: float
  3. Option C: String
  4. Option D: char
Show hint

C has primitive data types. String is a construct, not a built-in primitive type.

Show answer

Answer: C. String

In C, 'String' is not a built-in data type. The primitive data types in C are: (1) int (integers), (2) float (floating-point numbers), (3) char (single characters), (4) double (double-precision floating-point), (5) void. Strings in C are represented as arrays of characters (char arrays), not as a primitive type. For example: char str[] = "Hello"; creates a string. Unlike languages such as Java or Python that have a String class, C does not have a native string type. Strings are created using null-terminated char arrays. C provides string handling functions in the standard library (string.h) like strlen(), strcpy(), etc., but these work with char arrays, not a built-in String type. This is an important distinction for C programmers.

23. Which of the following is an example of indirect recursion?

NEC model set
  1. Option A: Function X calls itself directly
  2. Option B: Function X calls function Y, which calls function X
  3. Option C: Function X calls function X twice
  4. Option D: Function X calls no other functions
Show hint

Indirect recursion involves cycle through intermediate functions, not direct self-call.

Show answer

Answer: B. Function X calls function Y, which calls function X

An example of indirect recursion is function X calls function Y, which calls function X. Recursion types: (1) Direct - Function calls itself, (2) Indirect - Function calls another, which eventually calls original. Direct recursion: factorial(n) = n * factorial(n-1), function directly calls itself. Indirect recursion example: (1) Function A calls B, (2) Function B calls A, (3) Creates cycle A → B → A. Cycle length can vary: (1) Mutual recursion - A and B call each other (cycle 2), (2) Longer cycle - A → B → C → A (cycle 3), (3) Any length possible. How indirect recursion works: (1) A calls B with modified parameter, (2) B calls A with different parameter, (3) Base case must exist - Stop cycle, (4) Without base case - Infinite recursion. Example code pattern: function A(n) { if (n <= 0) return 0; return B(n-1); } function B(n) { if (n <= 0) return 0; return A(n-1); }. Detecting: (1) Direct - Obvious from function code, (2) Indirect - Requires tracing call chain, (3) Tools can detect - Call graph analysis. Stack behavior: (1) Each call adds stack frame, (2) Indirect recursion - Stack grows across functions, (3) Same recursion depth concern - Stack overflow risk, (4) Need base case - To unwind stack. Different from: (1) Direct recursion - Self-call, (2) Tail recursion - Last operation is recursive call, (3) Mutual recursion - Specific indirect case. Practical: (1) Less common than direct recursion, (2) Mutual recursion in parsing - A parses expression, B parses term, (3) State machines - Functions represent states. This demonstrates recursion complexity.

24. What is the process of converting high-level programming language code to machine or assembly level code called?

Recalled from Jan 2026 exam
  1. Option A: Interpretation
  2. Option B: Compilation
  3. Option C: Linking
  4. Option D: Loading
Show hint

Converting source code to lower-level code. What's this process?

Show answer

Answer: B. Compilation

Compilation is the process of converting high-level programming language code to machine or assembly level code. A compiler reads source code and translates it into executable machine code or intermediate code. Compilation happens before execution. Interpretation executes code line-by-line without pre-translation. Linking combines compiled object files. Loading places executable into memory for execution. Compilation produces standalone executables that run without the compiler. This is why compiled programs run faster than interpreted ones.

25. Which function is used to read a single character from the keyboard in C?

Recalled from Jan 2026 exam
  1. Option A: scanf()
  2. Option B: getchar()
  3. Option C: getch()
  4. Option D: gets()
Show hint

This function reads one character without pressing Enter. What is it?

Show answer

Answer: C. getch()

The getch() function is used to read a single character from the keyboard in C. getch() reads a character without waiting for Enter key, making it useful for immediate input in games and interactive programs. getchar() also reads a single character but waits for Enter. scanf() reads formatted input. gets() reads an entire string (unsafe). getch() is non-standard (mainly for DOS/Windows) but widely used. For portable code, getchar() is preferred.

26. What is an Identifier in C programming?

  1. Option A: A keyword that has a specific meaning in the language
  2. Option B: A symbol used to represent a variable, function, or structure in a C program
  3. Option C: A constant value that cannot be changed during program execution
  4. Option D: None of above
Show answer

Answer: B. A symbol used to represent a variable, function, or structure in a C program

27. What is a constant in C programming?

  1. Option A: A keyword that has a specific meaning in the language
  2. Option B: A symbol used to represent a variable, function, or structure in a C program
  3. Option C: A value that cannot be changed during program execution
  4. Option D: All of above
Show answer

Answer: C. A value that cannot be changed during program execution

28. What is an operator in C programming?

  1. Option A: A symbol used to perform operations on variables, constants, and expressions
  2. Option B: A symbol used to define variables, functions, and structures
  3. Option C: A symbol used to control the flow of a program
  4. Option D: None of above
Show answer

Answer: A. A symbol used to perform operations on variables, constants, and expressions

29. What are some examples of operators in C programming?

  1. Option A: Arithmetic, relational, logical, and bitwise operators
  2. Option B: Assignment, conditional, and loop operators
  3. Option C: Structural, pointer, and memory operators
  4. Option D: All of above
Show answer

Answer: A. Arithmetic, relational, logical, and bitwise operators

30. What is a keyword in C programming?

  1. Option A: A symbol used to perform operations on variables, constants, and expressions
  2. Option B: A symbol used to define variables, functions, and structures
  3. Option C: A word that has a specific meaning in the language and cannot be used as an identifier
  4. Option D: None of above
Show answer

Answer: C. A word that has a specific meaning in the language and cannot be used as an identifier

31. What are some examples of keywords in C programming?

  1. Option A: int, float, char, if, for, while
  2. Option B: add, subtract, multiply, divide, modulus
  3. Option C: input, output, execute, stop
  4. Option D: Both a and b
Show answer

Answer: A. int, float, char, if, for, while

32. What is the difference between keywords and identifiers in C programming?

  1. Option A: Keywords have a specific meaning in the language, while identifiers do not
  2. Option B: Keywords are used to define variables, functions, and structures, while identifiers are not
  3. Option C: Keywords cannot be used as identifiers, while identifiers can be used as keywords
  4. Option D: All of above
Show answer

Answer: C. Keywords cannot be used as identifiers, while identifiers can be used as keywords

33. What is the difference between constants and variables in C programming?

  1. Option A: Constants have a fixed value that cannot be changed, while variables have a value that can be changed
  2. Option B: Constants are used to perform operations, while variables are used to store data
  3. Option C: Constants are used to define functions, while variables are used to define structures
  4. Option D: All of above
Show answer

Answer: A. Constants have a fixed value that cannot be changed, while variables have a value that can be changed

34. What is the difference between an operator and a function in C programming?

  1. Option A: An operator performs an operation on one or more operands, while a function performs a set of operations on input data
  2. Option B: A function performs an operation on one or more operands, while an operator performs a set of operations on input data
  3. Option C: Operators are written in uppercase, while functions are not
  4. Option D: Functions are written in uppercase, while operators are not
Show answer

Answer: A. An operator performs an operation on one or more operands, while a function performs a set of operations on input data

35. What is the purpose of a semicolon at the end of a statement in C programming?

  1. Option A: To indicate the end of a statement
  2. Option B: To separate two statements
  3. Option C: To define a function
  4. Option D: To declare a variable
Show answer

Answer: A. To indicate the end of a statement

36. What is a token in C programming?

  1. Option A: A symbol or keyword used in a C program
  2. Option B: A variable used in a C program
  3. Option C: A function used in a C program
  4. Option D: A structure used in a C program
Show answer

Answer: A. A symbol or keyword used in a C program

37. What are some examples of tokens in C programming?

  1. Option A: Keywords, identifiers, constants, and operators
  2. Option B: Functions, loops, and conditionals
  3. Option C: Variables, arrays, and structures
  4. Option D: All of above
Show answer

Answer: A. Keywords, identifiers, constants, and operators

38. What is the purpose of arithmetic operators in C programming?

  1. Option A: To perform basic mathematical operations such as addition, subtraction, multiplication, and division
  2. Option B: To compare values and make decisions based on the comparison results
  3. Option C: To manipulate bits and perform bitwise operations on binary data
  4. Option D: All of above
Show answer

Answer: A. To perform basic mathematical operations such as addition, subtraction, multiplication, and division

39. What is the purpose of relational operators in C programming?

  1. Option A: To perform basic mathematical operations such as addition, subtraction, multiplication, and division
  2. Option B: To compare values and make decisions based on the comparison results
  3. Option C: To manipulate bits and perform bitwise operations on binary data
  4. Option D: All of above
Show answer

Answer: B. To compare values and make decisions based on the comparison results

40. What is the purpose of logical operators in C programming?

  1. Option A: To perform basic mathematical operations such as addition, subtraction, multiplication, and division
  2. Option B: To compare values and make decisions based on the comparison results
  3. Option C: To perform logical operations such as AND, OR, and NOT on boolean values
  4. Option D: All of above
Show answer

Answer: C. To perform logical operations such as AND, OR, and NOT on boolean values

41. What is the purpose of bitwise operators in C programming?

  1. Option A: To perform basic mathematical operations such as addition, subtraction, multiplication, and division
  2. Option B: To compare values and make decisions based on the comparison results
  3. Option C: To manipulate bits and perform bitwise operations on binary data
  4. Option D: All of above
Show answer

Answer: C. To manipulate bits and perform bitwise operations on binary data

42. What is the difference between the logical AND operator (&&) and the bitwise AND operator (&) in C programming?

  1. Option A: The logical AND operator performs a logical operation on boolean values, while the bitwise AND operator performs a bitwise operation on binary data
  2. Option B: The logical AND operator performs a bitwise operation on boolean values, while the bitwise AND operator performs a logical operation on binary data
  3. Option C: There is no difference between the logical AND operator and the bitwise AND operator in C programming
  4. Option D: All of above
Show answer

Answer: A. The logical AND operator performs a logical operation on boolean values, while the bitwise AND operator performs a bitwise operation on binary data

43. What is the difference between the logical OR operator (||) and the bitwise OR operator (|) in C programming?

  1. Option A: The logical OR operator performs a logical operation on boolean values, while the bitwise OR operator performs a bitwise operation on binary data
  2. Option B: The logical OR operator performs a bitwise operation on boolean values, while the bitwise OR operator performs a logical operation on binary data
  3. Option C: There is no difference between the logical OR operator and the bitwise OR operator in C programming
  4. Option D: All of above
Show answer

Answer: A. The logical OR operator performs a logical operation on boolean values, while the bitwise OR operator performs a bitwise operation on binary data

44. What is the result of the following expression: 5 & 6

  1. Option A: 5
  2. Option B: 6
  3. Option C: 4
  4. Option D: 1
Show answer

Answer: C. 4

45. What is the result of the following expression: 5<6

  1. Option A: 0
  2. Option B: 1
  3. Option C: True
  4. Option D: False
Show answer

Answer: B. 1

46. What is the purpose of the conditional operator (?:) in C programming?

  1. Option A: To perform a conditional operation based on the value of a condition
  2. Option B: To perform arithmetic operations
  3. Option C: To declare a variable
  4. Option D: To assign a value to a variable
Show answer

Answer: A. To perform a conditional operation based on the value of a condition

47. What is the difference between the bitwise AND operator (&) and the bitwise OR operator (|) in C programming?

  1. Option A: The bitwise AND operator performs a bitwise AND operation, while the bitwise OR operator performs a bitwise OR operation
  2. Option B: The bitwise OR operator performs a bitwise AND operation, while the bitwise AND operator performs a bitwise OR operation
  3. Option C: Bitwise AND operators are written in uppercase, while bitwise OR operators are not
  4. Option D: Bitwise OR operators are written in uppercase, while bitwise AND operators are not
Show answer

Answer: A. The bitwise AND operator performs a bitwise AND operation, while the bitwise OR operator performs a bitwise OR operation

48. What is the purpose of the assignment operator (=) in C programming?

  1. Option A: To compare two values
  2. Option B: To assign a value to a variable
  3. Option C: To perform mathematical operations
  4. Option D: To declare a variable
Show answer

Answer: B. To assign a value to a variable

49. What is the result of the following expression: 5 + 7 * 2

  1. Option A: 19
  2. Option B: 26
  3. Option C: 16
  4. Option D: 9
Show answer

Answer: A. 19

50. What is the difference between formatted and unformatted input/output in C programming?

  1. Option A: Formatted input/output is used to input/output data in a specific format, while unformatted input/output is used to input/output data without any format.
  2. Option B: Formatted input/output is used to input/output data without any format, while unformatted input/output is used to input/output data in a specific format.
  3. Option C: There is no difference between formatted and unformatted input/output in C programming.
  4. Option D: None of above
Show answer

Answer: A. Formatted input/output is used to input/output data in a specific format, while unformatted input/output is used to input/output data without any format.

51. What are some examples of formatted input functions in C programming?

  1. Option A: scanf(), gets(), and fscanf()
  2. Option B: getchar(), gets(), and fgetc()
  3. Option C: printf(), puts(), and fprintf()
  4. Option D: All of above
Show answer

Answer: A. scanf(), gets(), and fscanf()

52. What are some examples of formatted output functions in C programming?

  1. Option A: scanf(), gets(), and fscanf()
  2. Option B: getchar(), gets(), and fgetc()
  3. Option C: printf(), puts(), and fprintf()
  4. Option D: All of above
Show answer

Answer: C. printf(), puts(), and fprintf()

53. What is the purpose of the scanf() function in C programming?

  1. Option A: To output data to the standard output device
  2. Option B: To input data from the standard input device
  3. Option C: To input/output data to/from a file
  4. Option D: All of above
Show answer

Answer: B. To input data from the standard input device

54. What is the purpose of the printf() function in C programming?

  1. Option A: To output data to the standard output device
  2. Option B: To input data from the standard input device
  3. Option C: To input/output data to/from a file
  4. Option D: All of above
Show answer

Answer: A. To output data to the standard output device

55. What is the difference between the gets() and scanf() functions in C programming?

  1. Option A: The gets() function inputs data without any format, while the scanf() function inputs data in a specific format.
  2. Option B: The gets() function inputs data in a specific format, while the scanf() function inputs data without any format.
  3. Option C: There is no difference between the gets() and scanf() functions in C programming.
  4. Option D: Both a and b
Show answer

Answer: A. The gets() function inputs data without any format, while the scanf() function inputs data in a specific format.

56. What is the difference between the puts() and printf() functions in C programming?

  1. Option A: The puts() function outputs data without any format, while the printf() function outputs data in a specific format.
  2. Option B: The puts() function outputs data in a specific format, while the printf() function outputs data without any format.
  3. Option C: There is no difference between the puts() and printf() functions in C programming.
  4. Option D: Both a and b
Show answer

Answer: A. The puts() function outputs data without any format, while the printf() function outputs data in a specific format.

57. What is the standard library function used to read a string from the user in C?

  1. Option A: scanf()
  2. Option B: gets()
  3. Option C: fgets()
  4. Option D: sprintf()
Show answer

Answer: B. gets()

58. Which of the following functions is used to print a string to the screen in C?

  1. Option A: puts()
  2. Option B: printf()
  3. Option C: fprintf()
  4. Option D: getchar()
Show answer

Answer: A. puts()

59. What is the purpose of the %d format specifier in the printf() function in C?

  1. Option A: To print an integer
  2. Option B: To print a string
  3. Option C: To print a float
  4. Option D: To print a double
Show answer

Answer: A. To print an integer

60. What is the purpose of the %f format specifier in the printf() function in C?

  1. Option A: To print an integer
  2. Option B: To print a string
  3. Option C: To print a float
  4. Option D: To print a double
Show answer

Answer: C. To print a float

61. What is the purpose of the %lf format specifier in the printf() function in C?

  1. Option A: To print a string
  2. Option B: To print an integer
  3. Option C: To print a float
  4. Option D: To print a double
Show answer

Answer: D. To print a double

62. Which of the following functions is used to read a single character from the standard input in C?

  1. Option A: scanf()
  2. Option B: gets()
  3. Option C: getchar()
  4. Option D: fgetc()
Show answer

Answer: C. getchar()

63. What is the purpose of the if statement in C programming?

  1. Option A: To execute a block of code only if a certain condition is met
  2. Option B: To execute a block of code only if a certain condition is not met
  3. Option C: To execute a block of code if a certain condition is true
  4. Option D: None of the above
Show answer

Answer: C. To execute a block of code if a certain condition is true

64. What is the purpose of the else statement in C programming?

  1. Option A: To execute a block of code regardless of the condition
  2. Option B: To execute a block of code if a condition is false
  3. Option C: To terminate the program if a condition is false
  4. Option D: To skip a block of code if a condition is true
Show answer

Answer: B. To execute a block of code if a condition is false

65. What is the purpose of the switch statement in C programming?

  1. Option A: To execute one of several blocks of code based on the value of an expression
  2. Option B: To execute all of the blocks of code in a switch statement
  3. Option C: To execute only the first block of code in a switch statement
  4. Option D: None of the above
Show answer

Answer: A. To execute one of several blocks of code based on the value of an expression

66. What is the purpose of the break statement in C programming?

  1. Option A: To exit a loop
  2. Option B: To exit a switch statement
  3. Option C: To exit a function
  4. Option D: To exit the program
Show answer

Answer: B. To exit a switch statement

67. What is the purpose of the continue statement in C programming?

  1. Option A: To exit a loop
  2. Option B: To exit a switch statement
  3. Option C: To skip an iteration of a loop
  4. Option D: To exit the program
Show answer

Answer: C. To skip an iteration of a loop

68. What is the purpose of the for loop in C programming?

  1. Option A: To execute a block of code a specified number of times
  2. Option B: To execute a block of code indefinitely
  3. Option C: To execute a block of code based on a condition
  4. Option D: None of the above
Show answer

Answer: A. To execute a block of code a specified number of times

69. What is the purpose of the while loop in C programming?

  1. Option A: To execute a block of code a specified number of times
  2. Option B: To execute a block of code indefinitely until a condition is met
  3. Option C: To execute a block of code based on a condition
  4. Option D: None of the above
Show answer

Answer: B. To execute a block of code indefinitely until a condition is met

70. What is an if statement in C programming used for?

  1. Option A: To execute a block of code only if a certain condition is met
  2. Option B: To execute a block of code only if a certain condition is not met
  3. Option C: To execute a block of code if a certain condition is met, and execute another block of code if the condition is not met
  4. Option D: To declare variables
Show answer

Answer: C. To execute a block of code if a certain condition is met, and execute another block of code if the condition is not met

71. What is the purpose of the do-while loop in C programming?

  1. Option A: To execute a block of code a specified number of times
  2. Option B: To execute a block of code indefinitely until a condition is met
  3. Option C: To execute a block of code at least once, and then repeatedly until a condition is met
  4. Option D: None of the above
Show answer

Answer: C. To execute a block of code at least once, and then repeatedly until a condition is met

72. What is the difference between the for loop and the while loop in C programming?

  1. Option A: The for loop is used for a specified number of iterations, while the while loop is used until a condition is met
  2. Option B: The for loop is used until a condition is met, while the while loop is used for a specified number of iterations
  3. Option C: Both loops have the same functionality
  4. Option D: None of the above
Show answer

Answer: A. The for loop is used for a specified number of iterations, while the while loop is used until a condition is met

73. What does the "if" statement in C do?

  1. Option A: Executes a block of code if a condition is true
  2. Option B: Executes a block of code regardless of the condition
  3. Option C: Skips a block of code if a condition is false
  4. Option D: Terminates the program if a condition is true
Show answer

Answer: A. Executes a block of code if a condition is true

74. What is the syntax of the "if" statement in C?

  1. Option A: if (condition) { statements }
  2. Option B: if condition { statements }
  3. Option C: if {condition} (statements)
  4. Option D: if (condition) { statements };
Show answer

Answer: A. if (condition) { statements }

75. What is the purpose of the "else" statement in C?

  1. Option A: To execute a block of code if a condition is false
  2. Option B: To execute a block of code regardless of the condition
  3. Option C: To execute a block of code if the condition in the if statement is true
  4. Option D: To execute a block of code if the condition in the if statement is false
Show answer

Answer: D. To execute a block of code if the condition in the if statement is false

76. What is the syntax of the "switch" statement in C?

  1. Option A: switch (expression) { case constant-expression: statements; break; default: statements; }
  2. Option B: switch expression { case constant-expression: statements; break; default: statements; }
  3. Option C: switch (expression) case constant-expression: statements; break; default: statements;
  4. Option D: switch expression case constant-expression: statements; break; default: statements;
Show answer

Answer: A. switch (expression) { case constant-expression: statements; break; default: statements; }

77. What is the index of the first element in a one-dimensional array in C?

  1. Option A: 0
  2. Option B: 1
  3. Option C: 2
  4. Option D: 3
Show answer

Answer: A. 0

78. What is the syntax for declaring a two-dimensional integer array of size 3x4 in C?

  1. Option A: int arr[3][4];
  2. Option B: int arr[4][3];
  3. Option C: int arr[3,4];
  4. Option D: int arr[4,3];
Show answer

Answer: A. int arr[3][4];

79. How can you access the value of the 3rd element of the 2nd row of a two-dimensional array in C?

  1. Option A: arr[1][2]
  2. Option B: arr[2][1]
  3. Option C: arr[2][3]
  4. Option D: arr[3][2]
Show answer

Answer: A. arr[1][2]

80. What is the difference between a one-dimensional array and a two-dimensional array in C?

  1. Option A: A one-dimensional array has one row and multiple columns, whereas a two-dimensional array has multiple rows and multiple columns.
  2. Option B: A one-dimensional array has multiple rows and multiple columns, whereas a two-dimensional array has one row and multiple columns.
  3. Option C: A one-dimensional array has multiple rows and one column, whereas a two-dimensional array has one row and one column.
  4. Option D: A one-dimensional array has one row and one column, whereas a two-dimensional array has multiple rows and multiple columns.
Show answer

Answer: A. A one-dimensional array has one row and multiple columns, whereas a two-dimensional array has multiple rows and multiple columns.

81. What is the syntax for initializing a one-dimensional array in C?

  1. Option A: int arr[] = {1,2,3,4,5};
  2. Option B: int arr[5] = (1,2,3,4,5);
  3. Option C: int arr[5] = {1,2,3,4};
  4. Option D: int arr = {1, 2, 3, 4, 5};
Show answer

Answer: A. int arr[] = {1,2,3,4,5};

82. How can you find the number of elements in a one-dimensional array in C?

  1. Option A: sizeof(arr)
  2. Option B: sizeof(arr[0])
  3. Option C: sizeof(arr)/sizeof(arr[0])
  4. Option D: sizeof(arr[])/sizeof(arr[0])
Show answer

Answer: C. sizeof(arr)/sizeof(arr[0])

83. What is the syntax for declaring a multidimensional array in C?

  1. Option A: int arr[][][];
  2. Option B: int arr;
  3. Option C: int arr[];
  4. Option D: int arr[...][...][...];
Show answer

Answer: D. int arr[...][...][...];

84. What is the use of the strlen() function in C when working with arrays?

  1. Option A: To find the length of a one-dimensional array
  2. Option B: To find the length of a two-dimensional array
  3. Option C: To find the length of a string
  4. Option D: To find the length of a multidimensional array
Show answer

Answer: C. To find the length of a string

85. What is a one-dimensional array in C?

  1. Option A: A set of values of the same data type stored in a contiguous block of memory
  2. Option B: A set of values of different data types stored in a contiguous block of memory
  3. Option C: A set of values of the same data type stored in non-contiguous memory locations
  4. Option D: A set of values of different data types stored in non-contiguous memory locations
Show answer

Answer: A. A set of values of the same data type stored in a contiguous block of memory

86. How can you access the value at the third position of a one-dimensional array named "array"?

  1. Option A: array[2]
  2. Option B: array[3]
  3. Option C: array[0]
  4. Option D: array[1]
Show answer

Answer: A. array[2]

87. What is a two-dimensional array in C?

  1. Option A: An array of arrays
  2. Option B: A set of values of the same data type stored in non-contiguous memory locations
  3. Option C: A set of values of different data types stored in a contiguous block of memory
  4. Option D: A set of values of the same data type stored in a single contiguous block of memory
Show answer

Answer: A. An array of arrays

88. How can you access the value at the first row and second column of a two-dimensional array named "array"?

  1. Option A: array[0][1]
  2. Option B: array[1][0]
  3. Option C: array[1][2]
  4. Option D: array[2][1]
Show answer

Answer: A. array[0][1]

89. What is a multidimensional array in C?

  1. Option A: An array of arrays of arrays
  2. Option B: A set of values of different data types stored in non-contiguous memory locations
  3. Option C: A set of values of the same data type stored in a single contiguous block of memory
  4. Option D: A set of values of different data types stored in a single contiguous block of memory
Show answer

Answer: A. An array of arrays of arrays

90. What is the difference between a one-dimensional array and a two-dimensional array in C?

  1. Option A: A two-dimensional array has more dimensions than a one-dimensional array
  2. Option B: A one-dimensional array has more dimensions than a two-dimensional array
  3. Option C: There is no difference between a one-dimensional array and a two-dimensional array
  4. Option D: A two-dimensional array can store more values than a one-dimensional array
Show answer

Answer: A. A two-dimensional array has more dimensions than a one-dimensional array

91. What is a string in C programming?

  1. Option A: A sequence of characters enclosed in quotes
  2. Option B: An array of characters
  3. Option C: A single character
  4. Option D: None of above
Show answer

Answer: B. An array of characters

92. How can you find the length of a string in C programming?

  1. Option A: By using the length() function
  2. Option B: By using the strlen() function
  3. Option C: By using the sizeof() operator
  4. Option D: None of above
Show answer

Answer: B. By using the strlen() function

93. How can you concatenate two strings in C programming?

  1. Option A: By using the + operator
  2. Option B: By using the strcat() function
  3. Option C: By using the strcpy() function
  4. Option D: None of above
Show answer

Answer: B. By using the strcat() function

94. What does the strcpy() function do in C programming?

  1. Option A: Copies one string to another
  2. Option B: Concatenates two strings
  3. Option C: Compares two strings
  4. Option D: None of above
Show answer

Answer: A. Copies one string to another

95. What is the difference between the strcpy() and strcat() functions in C programming?

  1. Option A: strcpy() copies one string to another, while strcat() concatenates two strings
  2. Option B: strcpy() concatenates two strings, while strcat() copies one string to another
  3. Option C: Both functions copy one string to another
  4. Option D: None of above
Show answer

Answer: A. strcpy() copies one string to another, while strcat() concatenates two strings

96. How can you compare two strings in C programming?

  1. Option A: By using the strcmp() function
  2. Option B: By using the strcat() function
  3. Option C: By using the strcpy() function
  4. Option D: Both a and b
Show answer

Answer: A. By using the strcmp() function

97. What is the return value of the strcmp() function when two strings are equal?

  1. Option A: 0
  2. Option B: 1
  3. Option C: -1
  4. Option D: null
Show answer

Answer: A. 0

98. What is the return value of the strcmp() function when the first string is greater than the second string?

  1. Option A: 0
  2. Option B: 1
  3. Option C: -1
  4. Option D: null
Show answer

Answer: B. 1

99. What is the return value of the strcmp() function when the first string is less than the second string?

  1. Option A: 0
  2. Option B: 1
  3. Option C: -1
  4. Option D: null
Show answer

Answer: C. -1

100. How can you reverse a string in C programming?

  1. Option A: By using the strrev() function
  2. Option B: By using a loop and swapping characters
  3. Option C: There is no built-in function to reverse a string in C programming
  4. Option D: None of above
Show answer

Answer: B. By using a loop and swapping characters

101. What is the purpose of the strcat() function in C programming?

  1. Option A: To copy a string to another string.
  2. Option B: To concatenate two strings.
  3. Option C: To find the length of a string.
  4. Option D: To compare two strings.
Show answer

Answer: B. To concatenate two strings.

102. What is the purpose of the strcmp() function in C programming?

  1. Option A: To copy a string to another string.
  2. Option B: To find the length of a string.
  3. Option C: To concatenate two strings.
  4. Option D: To compare two strings.
Show answer

Answer: D. To compare two strings.

103. What is the purpose of the strcpy() function in C programming?

  1. Option A: To copy a string to another string.
  2. Option B: To find the length of a string.
  3. Option C: To concatenate two strings.
  4. Option D: To compare two strings.
Show answer

Answer: A. To copy a string to another string.

104. What is the purpose of the strlen() function in C programming?

  1. Option A: To compare two strings.
  2. Option B: To concatenate two strings.
  3. Option C: To find the length of a string.
  4. Option D: To copy a string to another string.
Show answer

Answer: C. To find the length of a string.

105. What is the purpose of the strstr() function in C programming?

  1. Option A: To find a substring in a string.
  2. Option B: To compare two strings.
  3. Option C: To find the first occurrence of a character in a string.
  4. Option D: To reverse a string.
Show answer

Answer: A. To find a substring in a string.

106. How can you reverse a string in C programming?

  1. Option A: By using the strrev() function.
  2. Option B: By using a loop and swapping characters.
  3. Option C: By using the strcat() function.
  4. Option D: By using the strcmp() function.
Show answer

Answer: B. By using a loop and swapping characters.

107. How can you convert a string to uppercase in C programming?

  1. Option A: By using the toupper() function.
  2. Option B: By using a loop and converting each character.
  3. Option C: By using the strcat() function.
  4. Option D: By using the strcmp() function.
Show answer

Answer: B. By using a loop and converting each character.

108. How can you convert a string to lowercase in C programming?

  1. Option A: By using the tolower() function.
  2. Option B: By using a loop and converting each character.
  3. Option C: By using the strcat() function.
  4. Option D: By using the strcmp() function.
Show answer

Answer: B. By using a loop and converting each character.

109. What is the purpose of the sprintf() function in C programming?

  1. Option A: To format and store a string in a buffer.
  2. Option B: To concatenate two string
  3. Option C: To find the length of a string.
  4. Option D: To compare two strings.
Show answer

Answer: A. To format and store a string in a buffer.

110. What is the purpose of the sscanf() function in C programming?

  1. Option A: To read formatted input from a string.
  2. Option B: To concatenate two strings.
  3. Option C: To find the length of a string.
  4. Option D: To compare two strings.
Show answer

Answer: A. To read formatted input from a string.

3.2 Pointers, structures and data files in C

122 questions · ACtE0302

111. What does int *p = NULL mean in C++?

Aasadh 2081 exam
  1. Option A: p is a null pointer
  2. Option B: invalid assignment
  3. Option C: p is an integer
  4. Option D: p is a void pointer
Show hint

NULL represents no valid address.

Show answer

Answer: A. p is a null pointer

p is a null pointer pointing to no valid memory address.

112. What is the syntax for binary file writing in C?

  1. Option A: fp=fopen("abc.txt","wr");
  2. Option B: fp=fopen("abc.txt","wb");
  3. Option C: fp=fopen("abc.txt","wbin");
  4. Option D: fp=fopen("abc.txt","b");
Show hint

Binary mode adds 'b' to the mode string.

Show answer

Answer: B. fp=fopen("abc.txt","wb");

Correct syntax for binary write mode: fopen("filename", "wb") where 'w' means write and 'b' means binary.

113. Which C function finds current position in file?

  1. Option A: fseek()
  2. Option B: ftell()
  3. Option C: fgetpos()
  4. Option D: rewind()
Show hint

Returns file pointer position.

Show answer

Answer: B. ftell()

ftell() returns the current position of the file pointer in the file.

114. What does fwrite(str, strlen(str) + 1, 1, filePointer) do?

  1. Option A: Prints characters without null
  2. Option B: Prints all chars including null
  3. Option C: Writes string length
  4. Option D: Writes length plus one
Show hint

strlen(str) + 1 includes null terminator.

Show answer

Answer: B. Prints all chars including null

strlen(str) + 1 includes null character, so fwrite writes entire string with null terminator.

115. How do arrays and pointers relate in C?

  1. Option A: Arrays and pointers are completely unrelated
  2. Option B: Arrays decay to pointers when used in expressions
  3. Option C: Pointers are always faster than arrays
  4. Option D: Arrays cannot be used with pointers
Show hint

Consider how arr[i] relates to *(arr+i).

Show answer

Answer: B. Arrays decay to pointers when used in expressions

Arrays and pointers are intimately related in C. Array name represents address of first element (except with sizeof or &). When array appears in expression, it automatically converts (decays) to pointer to first element. Example: int arr[5]; declares array, arr is equivalent to &arr[0]. Pointer arithmetic: *(arr+i) is equivalent to arr[i]. Accessing: arr[3] translates to *(arr+3). This relationship is why functions receiving arrays get pointers: void func(int arr[]) is identical to void func(int *arr) - both receive pointer to array. Multi-dimensional arrays: int matrix[3][4]; matrix is pointer to array of 4 ints, matrix[i] is pointer to int, matrix[i][j] is int. Differences: sizeof(arr) gives total array size; sizeof(&arr[0]) gives pointer size. & on array: &arr gives pointer to whole array (type int (*)[5] for int arr[5]), not same as arr (type int*). String arrays: "hello" is array decaying to pointer to 'h'. Using this decay concept: for(int *p = arr; p < arr+5; p++) iterates through array using pointers. Understanding this relationship crucial for pointer arithmetic, function parameters, dynamic allocation patterns. Modern trend: using pointers more than arrays for flexibility, but understanding both essential.

116. What is pointer arithmetic in C?

  1. Option A: Arithmetic using pointer variables as operands
  2. Option B: Mathematical operations on addresses stored in pointers
  3. Option C: Calculations that pointers perform automatically
  4. Option D: Using pointers to store mathematical results
Show hint

When you do ptr+1, ptr-2, etc., what actually happens to the address?

Show answer

Answer: B. Mathematical operations on addresses stored in pointers

Pointer arithmetic involves mathematical operations on pointer values (addresses). Operations: increment (ptr++), decrement (ptr--), addition (ptr+n), subtraction (ptr-n), comparison (ptr1 < ptr2), difference (ptr1-ptr2). Crucial: increment/decrement scale by data type size. For int *p, p++ moves pointer by sizeof(int) bytes (usually 4), not 1 byte. Example: if p = 1000 (address), p++ becomes 1004 for int pointer. This scaling automatic based on pointer type. Pointer difference: (ptr2 - ptr1) gives number of elements between, not bytes. Uses: array traversal with pointers, dynamic array management, building linked lists. Allowed operations: ++ (increment), -- (decrement), +n (advance n positions), -n (retreat n positions), comparison (<, >, <=, >=), subtraction (two pointers), +=, -=. Disallowed: multiplication, division, addition of two pointers. Valid: comparison of pointers from same array, subtraction of pointers from same array. Out-of-bounds arithmetic: technically allowed but undefined behavior if dereferenced. Array iteration: for(int *p = arr; p < arr+5; ++p) uses pointer arithmetic. Void pointers: void *p cannot be incremented (don't know size). Understanding scaling essential for correct pointer operations and avoiding off-by-one errors.

117. How are pointers and arrays passed to functions?

  1. Option A: Arrays passed by value, pointers by reference
  2. Option B: Both decay to pointers, function receives address
  3. Option C: Arrays copy entire data, pointers send reference
  4. Option D: Different mechanisms for arrays and pointers
Show hint

When you pass arr[] to function, what does it actually receive?

Show answer

Answer: B. Both decay to pointers, function receives address

Arrays and pointers passed to functions share a common mechanism: arrays decay to pointers to first element. Function declaration: void func(int arr[10]) is identical to void func(int arr[]) and void func(int *arr) - all receive pointer to array's first element. This means: (1) Array size info lost in function - must pass size separately or use sentinel. (2) Modifications in function affect original array (passed by reference effectively). (3) No array copying occurs - efficient even for large arrays. Example: int arr[100]; func(arr) passes &arr[0], not entire array. For comparison: structs passed by value (copied) unless pointer passed, arrays always by reference. Multi-dimensional arrays: void func(int arr[][5]) receives pointer to array of 5 ints. Other dimensions required: void func(int (*ptr)[5][10]) for 3D array. Function pointers: void (*func)(int arr[]) can point to function receiving array. Return considerations: cannot return array from function (cannot create array on stack of unknown size), must return pointer to dynamically allocated array. For 2D arrays: void func(int **arr) works for ragged arrays, void func(int arr[][5]) for rectangular arrays. Understanding this decay crucial for function parameter design and memory safety.

118. What does passing pointers to functions enable?

  1. Option A: Better performance only
  2. Option B: Multiple return values and variable modification
  3. Option C: Faster array access
  4. Option D: Simpler function syntax
Show hint

If you want function to modify original variable or return multiple values, what do you pass?

Show answer

Answer: B. Multiple return values and variable modification

Passing pointers to functions enables multiple important capabilities: (1) Modifying caller's variables: void swap(int *a, int *b) can modify both arguments by dereferencing. (2) Multiple return values: instead of single return, use output parameters (pointers). Example: void divmod(int a, int b, int *quo, int *rem) returns quotient and remainder through pointers. (3) Dynamic memory allocation: allocate in function, pass pointer back. (4) Avoiding large data copies: pass pointer to large structure instead of copying entire structure. (5) Building complex data structures: linked lists, trees use pointers extensively. (6) Callback functions: pass function pointer for flexible function behavior. Pointer parameter patterns: input parameters (const int *), output parameters (int *), input-output (modify and use). Example: void double_it(int *x) { *x = *x * 2; } modifies original variable. Contrast with pass-by-value: void double_it(int x) { x = x * 2; } modifies only local copy. Dangers: null pointer dereference, dangling pointers (freed memory), uninitialized pointers. Best practices: validate pointer before use, use const for input-only pointers, document which parameters are output. Modern C: use const pointers for read-only, document intent clearly. In C++, references often preferred over pointers for cleaner syntax, but concept similar.

119. What is the difference between struct and union in C?

  1. Option A: No significant difference
  2. Option B: Struct allocates separate memory for each member, union shares memory
  3. Option C: Union is faster than struct
  4. Option D: Struct can have functions, union cannot
Show hint

Think about memory layout - do all members get their own space?

Show answer

Answer: B. Struct allocates separate memory for each member, union shares memory

Struct vs Union - fundamental difference in memory allocation: Struct: allocates memory for ALL members. struct Point { int x; int y; } has size = sizeof(int) + sizeof(int). Each member independent, all exist simultaneously. Access: point.x and point.y both valid. Union: members share same memory location. union Data { int i; float f; } has size = max(sizeof(int), sizeof(float)). Only one member can hold value at a time. Access: data.i or data.f, but setting one overwrites other. Use cases - Struct: grouping related data (person name, age, address). Union: memory-constrained systems, hardware registers (different data types in same location), variant data types. Example: network packet header (fixed fields in struct) vs hardware register (different interpretations in union). Padding/alignment: struct size ≥ sum of members (compiler adds padding), union size = largest member. Union efficiency: saves memory (only one variant active), but requires careful management. Nested: union within struct or vice versa possible. Sizeof: struct A { int x; char c; } likely 8 bytes (int 4 + char 1 + padding 3). Union U { int x; char c; } size 4 (max of int/char). Accessing wrong union member returns garbage - type safety burden on programmer. C doesn't enforce which union member is active. Tagged unions (struct with int tag and union) provide safe variant handling. Useful in interpreters, protocol implementations, embedded systems.

120. What is an array of structures in C?

  1. Option A: Array containing different data types
  2. Option B: Array where each element is a structure
  3. Option C: Structure containing multiple arrays
  4. Option D: Array of pointers to structures
Show hint

Like a table where each row is a structure instance.

Show answer

Answer: B. Array where each element is a structure

Array of structures: array where each element is a structure instance. Declaration: struct Student { char name[50]; int id; float gpa; } students[100]; creates array of 100 Student structures. Memory: contiguous block where each Student occupies sizeof(struct Student) bytes. Accessing: students[0].name accesses name of first student, students[i].id accesses id of i-th student. Nested: structure already contains arrays (name[50] is array within structure). Initialization: struct Student s[3] = { {"Alice", 1, 3.8}, {"Bob", 2, 3.5}, {"Charlie", 3, 3.9} }; Iteration: for(int i=0; i<100; i++) process_student(&students[i]); Passing: arrays decay to pointers, so function receives struct Student *arr. Sorting: qsort(students, 100, sizeof(struct Student), compare_func) sorts array. Comparison function: int compare_func(const void *a, const void *b) { return ((struct Student*)a)->id - ((struct Student*)b)->id; }. Dynamic allocation: struct Student *arr = malloc(n * sizeof(struct Student)); for flexible sizing. Advantages: organize related data (each student's complete info), efficient storage (contiguous memory), cache-friendly access. Common in: databases (records), game development (entities), scientific computing (datasets). Understanding memory layout crucial for pointer arithmetic and efficient access patterns.

121. How are structures passed to functions?

  1. Option A: Structures always passed by value (copied)
  2. Option B: Structures passed by value by default, by pointer if specified
  3. Option C: Structures always passed by reference
  4. Option D: Only pointers to structures can be passed
Show hint

What happens - does entire structure get copied or just address?

Show answer

Answer: B. Structures passed by value by default, by pointer if specified

Structures passed to functions by value by default - entire structure copied to function's stack frame. void process(struct Student s) receives copy of s, modifications don't affect original. For large structures, this copying is inefficient. Alternative: pass by pointer - void process(struct Student *s) receives address only, modifies original. Pointer parameters: void set_id(struct Student *s, int id) { s->id = id; } modifies original through pointer. Accessing pointer members: use -> operator (s->id) instead of . operator (s.id). Efficiency: for structures > 2-3 pointers, pass by pointer preferred. Const pointers: void display(const struct Student *s) for read-only access, compiler prevents modifications. Return values: functions can return structures by value (struct Student create_student()) but inefficient for large structures. Pattern: for output parameters, use pointers (void func(struct Student *out)). Dynamic allocation: struct Student *s = malloc(sizeof(struct Student)); then pass s to functions. Array of structures: arrays passed as pointers automatically (struct Student arr[100] becomes struct Student *arr in function). Memory consideration: stack limited, large structure copies waste stack space. Rule of thumb: pass primitive types by value, structures/arrays by pointer. Modern practice: C++ uses references for cleaner syntax, but concept similar. Understanding calling convention crucial for performance and correctness.

122. What is the relationship between structure and pointer in C?

  1. Option A: No relationship - different concepts
  2. Option B: Pointers point to structures, enabling dynamic allocation and modification
  3. Option C: Structures contain pointers only
  4. Option D: Pointers store structure data
Show hint

How do you work with structures dynamically? How do you access structure members through pointers?

Show answer

Answer: B. Pointers point to structures, enabling dynamic allocation and modification

Structures and pointers closely related: pointers point to structures, enabling dynamic allocation, flexible data structures, and efficient passing. Pointer to structure: struct Student *ptr; or struct Student *ptr = &s; Accessing members: ptr->field (equivalent to (*ptr).field). Arrow operator -> preferred for readability. Dynamic allocation: struct Student *ptr = malloc(sizeof(struct Student)); ptr->id = 1; creates structure on heap. Linked structures: struct Node { int data; struct Node *next; } builds linked lists. Self-referential structures use pointers to own type. Pointer arrays: struct Student *students[100] - array of pointers, flexible sizing. Dynamic array: struct Student **arr = malloc(n * sizeof(struct Student*)); for array of pointers to structures. Typedef for cleaner syntax: typedef struct { int x; int y; } Point; then Point *p; Advantages: dynamic memory (allocate/deallocate as needed), data structure building (linked lists, trees), efficient passing (no copying). Memory layout: structure pointer stores address, accessing member calculates offset. Null check essential: if(ptr != NULL) before accessing members. Linked structures: struct Node { int data; struct Node *left; struct Node *right; } enables trees. Common pattern: struct with function pointers for object-oriented behavior. Understanding pointer-structure relationship crucial for building complex data structures and dynamic memory management.

123. What are file operations in C?

  1. Option A: Manipulating data within files
  2. Option B: Creating and deleting files only
  3. Option C: Opening, reading, writing, and closing files
  4. Option D: Encrypting file contents
Show hint

Think about complete file lifecycle - from opening to closing.

Show answer

Answer: C. Opening, reading, writing, and closing files

File operations involve complete file handling cycle: (1) Opening: FILE *fp = fopen("file.txt", "r") opens file (modes: r-read, w-write, a-append, r+, w+, a+); (2) Reading: fgetc(fp) reads character, fgets(line, size, fp) reads line, fread(buffer, size, count, fp) reads binary; (3) Writing: fputc(c, fp) writes character, fputs(line, fp) writes line, fwrite(buffer, size, count, fp) writes binary; (4) Closing: fclose(fp) closes file, flushing buffers. File pointer: FILE * represents stream, maintains file state (position, EOF, error). Status checking: feof(fp) checks end-of-file, ferror(fp) checks errors, fgetc returns EOF (-1) at end. Seeking: fseek(fp, offset, origin) positions pointer (origins: SEEK_SET start, SEEK_CUR current, SEEK_END end). ftell(fp) returns current position. rewind(fp) goes to start. Modes: text mode handles newline conversion, binary mode preserves exact bytes. Common patterns: while(!feof(fp)) { /* read */ } or while(fgets(line, sizeof(line), fp)) { /* process */ }. Error handling: check return values, validate file opened successfully. File operations essential for data persistence, logging, configuration files. Binary vs Text: text for human-readable data, binary for fixed-size records, images, executables. Safety: always close files, even on error (use cleanup code or close in finally equivalent). Resource leaks: unclosed files waste OS resources. File I/O slower than memory access - buffer strategically for performance.

124. What is sequential access to files in C?

  1. Option A: Accessing file from beginning only
  2. Option B: Reading/writing file from start to end in order
  3. Option C: Accessing file records randomly
  4. Option D: Accessing file through pointers
Show hint

You process file data in order, not jumping around - like reading book page by page.

Show answer

Answer: B. Reading/writing file from start to end in order

Sequential access: reading/writing file data from beginning to end in order, without skipping or jumping. Suitable for: text files, log files, data streams where linear processing sufficient. Example: FILE *fp = fopen("data.txt", "r"); while(fgets(line, sizeof(line), fp)) { process(line); } reads entire file sequentially. Characteristics: simple, efficient for full-file processing, natural for streaming. Operations: fgetc (next character), fgets (next line), fread (next block). Position: always moves forward, fseek seldom used. Search: to find specific record, must read from start (O(n) complexity). Advantages: straightforward logic, suitable for large files (memory-efficient streaming), commonly used for text processing. Disadvantages: inefficient for finding specific records, must re-read from start for multiple passes. Contrast with random access: jumping to specific record using fseek. Performance: sequential often faster than random due to disk head positioning and prefetching. Common uses: log file analysis, data import/export, stream processing, ETL (extract-transform-load). Implementation: maintain state variables for custom record format. Combined approach: sequential for parsing, random for specific lookups if structure known. Error handling: feof(), ferror() for end-of-file and error detection. Understanding sequential vs random access helps choose appropriate file handling strategy.

125. What is random access to files in C?

  1. Option A: Accessing file data in any order
  2. Option B: Using fseek to position file pointer at specific location
  3. Option C: Reading file without sequence
  4. Option D: Accessing random file from system
Show hint

You can jump to specific positions in file using fseek.

Show answer

Answer: B. Using fseek to position file pointer at specific location

Random access: jumping directly to specific file position without reading from start. Enabled by fseek(): fseek(fp, offset, whence) positions file pointer. Whence values: SEEK_SET (beginning, offset 0), SEEK_CUR (current position), SEEK_END (end of file). Examples: fseek(fp, 100, SEEK_SET) moves to byte 100; fseek(fp, -10, SEEK_CUR) moves back 10 bytes; fseek(fp, 0, SEEK_END) moves to end. Fixed-record files: if records are fixed size (e.g., 256 bytes each), random access efficient: fseek(fp, record_num * 256, SEEK_SET) jumps directly to record. ftell(): returns current position (bytes from start). rewind(): equivalent to fseek(fp, 0, SEEK_SET). Binary files: random access natural, text files problematic (variable-length records). Use case: database files, lookup by record number, editing specific portion. Advantages: O(1) access to any record (vs O(n) sequential), efficient for large files with specific record access. Disadvantages: requires fixed structure or index, not suitable for streaming. Typical pattern: open file, fseek to position, fread block, modify, fseek to original position, fwrite. Implementation detail: some systems (non-seekable) don't support fseek (pipes, sockets). Error checking: fseek returns 0 on success, non-zero on failure. Index files: separate index stores record positions for efficient lookup. Comparison with sequential: sequential simple but slow for specific records; random fast for lookups but requires structure. Modern databases use both: indexes (fast lookup) and sequential scans (bulk operations).

126. What is the size of a pointer in C?

NEC model set
  1. Option A: 1 byte
  2. Option B: 2 bytes
  3. Option C: 4 bytes
  4. Option D: It depends on the system architecture
Show hint

Pointer size varies with the operating system and processor architecture. Think about 32-bit vs 64-bit systems.

Show answer

Answer: D. It depends on the system architecture

The size of a pointer in C depends on the system architecture. On 32-bit systems, pointers are typically 4 bytes (32 bits), while on 64-bit systems, pointers are typically 8 bytes (64 bits). This is because pointers store memory addresses, and the address space size determines pointer size. A pointer must be large enough to address all available memory. On a 32-bit system with 4 GB maximum addressable memory, 4 bytes (32 bits) are sufficient. On a 64-bit system, 8 bytes are needed for larger address spaces. The size() operator can determine pointer size: printf("%zu", sizeof(int*)); typically outputs 4 (on 32-bit) or 8 (on 64-bit). Specialized architectures may use different pointer sizes. This architecture-dependence is important when writing portable C code.

127. What is the purpose of the fscanf() function in C programming?

  1. Option A: To input data from the standard input device
  2. Option B: To output data to the standard output device
  3. Option C: To input/output data to/from a file
  4. Option D: All of above
Show answer

Answer: C. To input/output data to/from a file

128. What is the difference between scanf() and fscanf() in C?

  1. Option A: scanf() reads from the standard input and fscanf() reads from a file
  2. Option B: scanf() reads from a file and fscanf() reads from the standard input
  3. Option C: Both functions have the same functionality
  4. Option D: None of the above
Show answer

Answer: A. scanf() reads from the standard input and fscanf() reads from a file

129. What is the purpose of the fopen() function in C?

  1. Option A: To open a file for reading
  2. Option B: To open a file for writing
  3. Option C: To open a file for reading and writing
  4. Option D: None of the above
Show answer

Answer: A. To open a file for reading

130. What is the purpose of the fclose() function in C?

  1. Option A: To close a file that was opened for reading
  2. Option B: To close a file that was opened for writing
  3. Option C: To close a file that was opened for reading and writing
  4. Option D: None of the above
Show answer

Answer: C. To close a file that was opened for reading and writing

131. What is the difference between fprintf() and sprintf() in C?

  1. Option A: fprintf() writes to a file and sprintf() writes to a string
  2. Option B: fprintf() writes to a string and sprintf() writes to a file
  3. Option C: Both functions have the same functionality
  4. Option D: None of the above
Show answer

Answer: A. fprintf() writes to a file and sprintf() writes to a string

132. What is the purpose of the "malloc" function in C programming?

  1. Option A: To free memory
  2. Option B: To allocate memory
  3. Option C: To initialize memory
  4. Option D: To reset memory
Show answer

Answer: B. To allocate memory

133. What is the purpose of the "free" function in C programming?

  1. Option A: To allocate memory
  2. Option B: To free memory
  3. Option C: To initialize memory
  4. Option D: To reset memory
Show answer

Answer: B. To free memory

134. What is the difference between an array and a pointer in C programming?

  1. Option A: An array is a set of values stored in a contiguous block of memory, while a pointer is a variable that stores the address of another variable
  2. Option B: A pointer is a set of values stored in a contiguous block of memory, while an array is a variable that stores the address of another variable
  3. Option C: There is no difference between an array and a pointer in C programming
  4. Option D: An array is a variable that stores the address of another variable, while a pointer is a set of values stored in a contiguous block of memory
Show answer

Answer: A. An array is a set of values stored in a contiguous block of memory, while a pointer is a variable that stores the address of another variable

135. What is the output of the following code? int a = 10; int *p = &a; printf("%p", p);

  1. Option A: 10
  2. Option B: 0
  3. Option C: Address of a
  4. Option D: Undefined
Show answer

Answer: C. Address of a

136. What is the output of the following code? int a = 10; int *p = &a; printf("%d", *p);

  1. Option A: 10
  2. Option B: 0
  3. Option C: Address of a
  4. Option D: Undefined
Show answer

Answer: A. 10

137. What is the correct way to declare a pointer to a character in C?

  1. Option A: char *str;
  2. Option B: char *str();
  3. Option C: char str*;
  4. Option D: char (*str)();
Show answer

Answer: A. char *str;

138. What is the output of the following code? int arr[5] = {1, 2, 3, 4, 5}; int *p = arr; printf("%d", *(p+3));

  1. Option A: 4
  2. Option B: 3
  3. Option C: 5
  4. Option D: Undefined
Show answer

Answer: A. 4

139. What is the output of the following code? int arr[5] = {1, 2, 3, 4, 5}; int *p = arr + 2; printf("%d", *(p-1));

  1. Option A: 2
  2. Option B: 3
  3. Option C: 4
  4. Option D: Undefined
Show answer

Answer: A. 2

140. What is the output of the following code? int a = 10; int *p = &a; int **q = &p; printf("%d", **q);

  1. Option A: 10
  2. Option B: 0
  3. Option C: Address of a
  4. Option D: Undefined
Show answer

Answer: A. 10

141. Which of the following is a valid way to declare a pointer to an integer array of size 5?

  1. Option A: int (*arr)[5];
  2. Option B: int *arr[5];
  3. Option C: int **arr[5];
  4. Option D: int arr*[5];
Show answer

Answer: A. int (*arr)[5];

142. What is the result of the following code? int arr[] = {1, 2, 3, 4}; int *p = arr + 1; printf("%d", *(p--));

  1. Option A: 2
  2. Option B: 1
  3. Option C: 3
  4. Option D: 4
Show answer

Answer: A. 2

143. What is the result of the following code? int arr[] = {1, 2, 3, 4}; int *p = arr + 2; printf("%d", *(--p));

  1. Option A: 2
  2. Option B: 1
  3. Option C: 3
  4. Option D: 4
Show answer

Answer: A. 2

144. What is the output of the following code? int arr[] = {1, 2, 3, 4}; int *p = arr; printf("%d", *p++);

  1. Option A: 1
  2. Option B: 2
  3. Option C: 3
  4. Option D: 4
Show answer

Answer: A. 1

145. Which of the following is true about pointer arithmetic in C?

  1. Option A: Addition and subtraction operations can be performed on pointers
  2. Option B: Multiplication and division operations can be performed on pointers
  3. Option C: Bitwise AND and OR operations can be performed on pointers
  4. Option D: None of the above
Show answer

Answer: A. Addition and subtraction operations can be performed on pointers

146. If 'ptr' is a pointer to an integer variable, what will be the output of the following code? printf("%d", ptr+1);

  1. Option A: The memory address of ptr
  2. Option B: The value of ptr
  3. Option C: The memory address of the integer variable ptr is pointing to
  4. Option D: The value of the integer variable ptr+1 is pointing to
Show answer

Answer: D. The value of the integer variable ptr+1 is pointing to

147. If 'ptr' is a pointer to an integer variable, what will be the output of the following code? printf("%d", *(ptr+1));

  1. Option A: The memory address of ptr
  2. Option B: The value of ptr
  3. Option C: The memory address of the integer variable ptr is pointing to
  4. Option D: The value of the integer variable ptr+1 is pointing to
Show answer

Answer: D. The value of the integer variable ptr+1 is pointing to

148. What is the result of the following code? int arr[] = {1, 2, 3, 4}; int *p = arr; printf("%d", *(p++));

  1. Option A: 1
  2. Option B: 2
  3. Option C: 3
  4. Option D: 4
Show answer

Answer: A. 1

149. What is the result of the following code? int arr[] = {1, 2, 3, 4}; int *p = arr; printf("%d", *(p-2));

  1. Option A: 1
  2. Option B: 2
  3. Option C: 3
  4. Option D: 4
Show answer

Answer: None of the options

The source’s answer, “Undefined”, is not one of the options.

150. What is the result of the following code? int arr[] = {1, 2, 3, 4}; int *p = arr; printf("%d", *(p+4));

  1. Option A: 1
  2. Option B: 3
  3. Option C: 4
  4. Option D: Undefined
Show answer

Answer: D. Undefined

151. What is the result of the following code? int a = 5, b = 10; int *p1 = &a; int *p2 = &b; int *temp; temp = p1; p1 = p2; p2 = temp; printf("%d %d", *p1, *p2);

  1. Option A: 5 10
  2. Option B: 10 5
  3. Option C: Undefined
  4. Option D: Error
Show answer

Answer: B. 10 5

152. What is the output of the following code? int a = 10; int *p = &a; (*p)++; printf("%d", a);

  1. Option A: 9
  2. Option B: 10
  3. Option C: 11
  4. Option D: Undefined
Show answer

Answer: C. 11

153. What is the result of the following code? int arr[] = {1, 2, 3, 4}; int *p = arr + 2; printf("%d", p[-1]);

  1. Option A: 1
  2. Option B: 2
  3. Option C: 3
  4. Option D: 4
Show answer

Answer: B. 2

154. What is the result of the following code? int arr[] = {1, 2, 3, 4, 5}; int *p = arr + 2; printf("%d", *p);

  1. Option A: 1
  2. Option B: 2
  3. Option C: 3
  4. Option D: 4
Show answer

Answer: C. 3

155. What is the data type of the pointer variable in the following code? char *p;

  1. Option A: char
  2. Option B: int
  3. Option C: float
  4. Option D: double
Show answer

Answer: A. char

156. What is the result of the following code? int x = 10, y = 20, z; int *p = &x, *q = &y; z = *p + (*q)++; printf("%d %d %d", x, y, z);

  1. Option A: 11 20 30
  2. Option B: 10 21 31
  3. Option C: 11 21 30
  4. Option D: 10 20 31
Show answer

Answer: None of the options

The source’s answer, “10 21 30”, is not one of the options.

157. What is the result of the following code? int arr[] = {1, 2, 3, 4, 5}; int *p = &arr[3]; printf("%d", *(p-2));

  1. Option A: 1
  2. Option B: 2
  3. Option C: 3
  4. Option D: 4
Show answer

Answer: B. 2

158. What is the result of the following code? int arr[] = {1, 2, 3, 4, 5}; int *p = arr; printf("%d", *(++p));

  1. Option A: 1
  2. Option B: 2
  3. Option C: 3
  4. Option D: 4
Show answer

Answer: B. 2

159. What is the result of the following code? int arr[] = {1, 2, 3, 4, 5}; int *p = arr; printf("%d", *(p+2));

  1. Option A: 1
  2. Option B: 2
  3. Option C: 3
  4. Option D: 4
Show answer

Answer: C. 3

160. Which of the following is true about structures in C?

  1. Option A: Structures can contain only variables of the same data type
  2. Option B: Structures can contain variables of different data types
  3. Option C: Structures cannot be passed as function arguments
  4. Option D: Structures cannot be returned by functions
Show answer

Answer: B. Structures can contain variables of different data types

161. How do you declare a structure in C?

  1. Option A: struct {name, age};
  2. Option B: struct (name, age);
  3. Option C: struct person { char name[20]; int age; };
  4. Option D: struct {person name, person age};
Show answer

Answer: C. struct person { char name[20]; int age; };

162. Which of the following is used to access the members of a structure?

  1. Option A: &
  2. Option B: .
  3. Option C: :
  4. Option D: ->
Show answer

Answer: B. .

163. How do you assign values to members of a structure in C?

  1. Option A: using the assignment operator
  2. Option B: using the dot operator
  3. Option C: using the arrow operator ->
  4. Option D: using the asterisk operator*
Show answer

Answer: A. using the assignment operator

164. What is the purpose of typedef in C structures?

  1. Option A: to declare a new variable
  2. Option B: to define a new data type
  3. Option C: to initialize a structure
  4. Option D: to allocate memory for a structure
Show answer

Answer: B. to define a new data type

165. Which of the following statements is true regarding the size of a structure in C?

  1. Option A: The size of a structure is the sum of the sizes of its members
  2. Option B: The size of a structure is always 4 bytes
  3. Option C: The size of a structure is the size of its largest member
  4. Option D: The size of a structure is the size of its smallest member
Show answer

Answer: A. The size of a structure is the sum of the sizes of its members

166. What is the operator used to dynamically allocate memory for a structure in C?

  1. Option A: .
  2. Option B: &
  3. Option C: ->
  4. Option D: malloc()
Show answer

Answer: D. malloc()

167. What is the operator used to deallocate memory allocated for a structure in C?

  1. Option A: &
  2. Option B: .
  3. Option C: free()
  4. Option D: calloc()
Show answer

Answer: C. free()

168. What is the purpose of a union in C?

  1. Option A: to combine multiple structures
  2. Option B: to create a new data type
  3. Option C: to declare a variable
  4. Option D: to share the same memory location for different data types
Show answer

Answer: D. to share the same memory location for different data types

169. Which of the following is true about nested structures in C?

  1. Option A: Nested structures are not allowed in C
  2. Option B: Nested structures can only contain variables of the same data type
  3. Option C: Nested structures can be defined inside another structure
  4. Option D: Nested structures can only contain pointers to other structures
Show answer

Answer: C. Nested structures can be defined inside another structure

170. What is a structure in C programming?

  1. Option A: A data type that groups variables of different types
  2. Option B: A data type that groups variables of the same type
  3. Option C: A data type that groups variables of the same size
  4. Option D: A data type that groups variables of different sizes
Show answer

Answer: A. A data type that groups variables of different types

171. What is the correct syntax to access a member of a nested structure?

  1. Option A: outer_structure.inner_structure.member_name
  2. Option B: inner_structure.member_name.outer_structure
  3. Option C: member_name.outer_structure.inner_structure
  4. Option D: None of the above
Show answer

Answer: A. outer_structure.inner_structure.member_name

172. What is the size of an empty structure in C programming?

  1. Option A: 0 bytes
  2. Option B: 1 byte
  3. Option C: 4 bytes
  4. Option D: 8 bytes
Show answer

Answer: A. 0 bytes

173. Which of the following is not a valid way to initialize a structure variable in C programming?

  1. Option A: struct book b = {"C Programming", "John Doe", 100};
  2. Option B: struct book b = {.name = "C Programming", .author = "John Doe", .price = 100};
  3. Option C: struct book b = {"C Programming", price=100};
  4. Option D: struct book b; b = {"C Programming", "John Doe", 100};
Show answer

Answer: D. struct book b; b = {"C Programming", "John Doe", 100};

174. What is a nested structure in C programming?

  1. Option A: A structure that has no members
  2. Option B: A structure that is defined inside another structure
  3. Option C: A structure that has only one member
  4. Option D: A structure that has members of different data types
Show answer

Answer: B. A structure that is defined inside another structure

175. In C programming, which keyword is used to define a structure?

  1. Option A: typedef
  2. Option B: define
  3. Option C: structdef
  4. Option D: struct
Show answer

Answer: D. struct

176. Which of the following statements is true about passing a structure to a function in C programming?

  1. Option A: Structures cannot be passed to a function.
  2. Option B: Structures are passed by value to a function.
  3. Option C: Structures are passed by reference to a function.
  4. Option D: Structures are passed as arrays to a function.
Show answer

Answer: B. Structures are passed by value to a function.

177. Which of the following is not a valid way to declare a pointer to a structure in C programming?

  1. Option A: struct *book b;
  2. Option B: struct book *b;
  3. Option C: typedef struct book *bookptr;
  4. Option D: typedef struct book booktype;
Show answer

Answer: A. struct *book b;

178. What is the keyword used to access the address of a structure variable in C programming?

  1. Option A: &
  2. Option B: *
  3. Option C: #
  4. Option D: $
Show answer

Answer: A. &

179. What is the main difference between a structure and a union in C programming?

  1. Option A: A structure allows for multiple members to be accessed at once, while a union only allows for one member to be accessed at a time.
  2. Option B: A union allows for multiple members to be accessed at once, while a structure only allows for one member to be accessed at a time.
  3. Option C: There is no difference between a structure and a union in C programming.
  4. Option D: None of above
Show answer

Answer: A. A structure allows for multiple members to be accessed at once, while a union only allows for one member to be accessed at a time.

180. Which of the following is the correct way to access a structure member using a pointer to a structure?

  1. Option A: structure_pointer->member_name
  2. Option B: *structure_pointer.member_name
  3. Option C: structure_pointer.member_name
  4. Option D: None of the above
Show answer

Answer: A. structure_pointer->member_name

181. What is the difference between passing a structure by value and passing a structure by pointer in C?

  1. Option A: When a structure is passed by value, any modifications made to it in the function are lost when the function returns. When a structure is passed by pointer, the modifications are retained.
  2. Option B: When a structure is passed by value, any modifications made to it in the function are retained when the function returns. When a structure is passed by pointer, the modifications are lost.
  3. Option C: There is no difference between passing a structure by value and passing a structure by pointer in C.
  4. Option D: None of the above
Show answer

Answer: A. When a structure is passed by value, any modifications made to it in the function are lost when the function returns. When a structure is passed by pointer, the modifications are retained.

182. In a union, how much memory is allocated for the union itself?

  1. Option A: The size of the largest member
  2. Option B: The size of all members combined
  3. Option C: The size of the smallest member
  4. Option D: The size of the union is not allocated in memory
Show answer

Answer: A. The size of the largest member

183. What is the main advantage of using a union over a structure?

  1. Option A: It uses less memory
  2. Option B: It is easier to declare and use
  3. Option C: It can hold more types of data
  4. Option D: It is faster to access its members
Show answer

Answer: A. It uses less memory

184. In a union, can two or more members be accessed simultaneously?

  1. Option A: Yes, always
  2. Option B: Yes, but only if they are of the same type
  3. Option C: No, only one member can be accessed at a time
  4. Option D: Yes, but only if the member is a pointer
Show answer

Answer: C. No, only one member can be accessed at a time

185. What is the purpose of declaring a bit field in a structure?

  1. Option A: To save memory
  2. Option B: To improve performance
  3. Option C: To store binary data
  4. Option D: To limit the number of possible values for a member
Show answer

Answer: A. To save memory

186. Can a structure or union contain a member that is itself a structure or union?

  1. Option A: Yes, there is no restriction on the type of members
  2. Option B: No, structures and unions cannot contain other structures or unions
  3. Option C: Yes, but only if the member is declared as static
  4. Option D: None of above
Show answer

Answer: A. Yes, there is no restriction on the type of members

187. How do you access a member of a structure or union using a pointer?

  1. Option A: -> operator
  2. Option B: . operator
  3. Option C: & operator
  4. Option D: * operator
Show answer

Answer: A. -> operator

188. In a union, what is the value of a member that was not explicitly set?

  1. Option A: Zero
  2. Option B: Garbage value
  3. Option C: Undefined
  4. Option D: The value of the previous member
Show answer

Answer: B. Garbage value

189. Which of the following statements is true about the size of a structure or union in C programming?

  1. Option A: The size of a structure or union is the sum of the sizes of its members
  2. Option B: The size of a structure or union is always a multiple of the size of its largest member
  3. Option C: The size of a structure or union depends on the alignment requirements of its members
  4. Option D: The size of a structure or union is always equal to the size of its largest member
Show answer

Answer: C. The size of a structure or union depends on the alignment requirements of its members

190. What is the difference between a structure and a union in C programming?

  1. Option A: A structure allows for multiple members to be accessed at once, while a union only allows for one member to be accessed at a time.
  2. Option B: A union allows for multiple members to be accessed at once, while a structure only allows for one member to be accessed at a time.
  3. Option C: There is no difference between a structure and a union in C programming.
  4. Option D: None of above
Show answer

Answer: A. A structure allows for multiple members to be accessed at once, while a union only allows for one member to be accessed at a time.

191. What is the size of a structure in C programming?

  1. Option A: The size of a structure is equal to the sum of the sizes of its members.
  2. Option B: The size of a structure is equal to the size of its largest member.
  3. Option C: The size of a structure is equal to the size of its smallest member.
  4. Option D: None of above
Show answer

Answer: A. The size of a structure is equal to the sum of the sizes of its members.

192. How do you access a member of a structure in C programming?

  1. Option A: Using the dot (.) operator.
  2. Option B: Using the arrow (->) operator.
  3. Option C: Using the asterisk (*) operator.
  4. Option D: None of above
Show answer

Answer: A. Using the dot (.) operator.

193. What is the keyword used to define a structure in C programming?

  1. Option A: struct
  2. Option B: union
  3. Option C: typedef
  4. Option D: None of above
Show answer

Answer: A. struct

194. Which of the following statements about unions is true in C programming?

  1. Option A: Unions can contain members of different types.
  2. Option B: Unions cannot contain members.
  3. Option C: Unions can only contain members of the same type.
  4. Option D: None of above
Show answer

Answer: A. Unions can contain members of different types.

195. What is the difference between a structure and a typedef struct in C programming?

  1. Option A: There is no difference.
  2. Option B: Typedef struct can only be used to define new data types.
  3. Option C: Typedef struct is a faster way to create a new structure type.
  4. Option D: None of above
Show answer

Answer: C. Typedef struct is a faster way to create a new structure type.

196. Can a structure contain a pointer to itself in C programming?

  1. Option A: Yes
  2. Option B: No
  3. Option C: It depends on the compiler used.
  4. Option D: It depends on Interpreter used.
Show answer

Answer: A. Yes

197. Which of the following statements is true about the alignment of structure members in C programming?

  1. Option A: Members of a structure are always aligned to the nearest byte boundary.
  2. Option B: Members of a structure are aligned based on their size and type.
  3. Option C: Members of a structure are not aligned in C programming.
  4. Option D: None of above
Show answer

Answer: B. Members of a structure are aligned based on their size and type.

198. What is the purpose of a bit-field in a structure in C programming?

  1. Option A: To allow the structure to store more data than its size would normally allow.
  2. Option B: To create a member that is only one bit in size.
  3. Option C: To allow the structure to be accessed in a bit-wise manner.
  4. Option D: None of above
Show answer

Answer: B. To create a member that is only one bit in size.

199. Which of the following is an example of a valid structure declaration in C programming?

  1. Option A: struct person {char name[50]; int age;}
  2. Option B: struct person (char name[50]; int age;)
  3. Option C: person_struct {char name[50]; int age;}
  4. Option D: None of above
Show answer

Answer: A. struct person {char name[50]; int age;}

200. What is the syntax for declaring an array of structures in C?

  1. Option A: struct array_name[size];
  2. Option B: array_name[size] struct;
  3. Option C: array_name[size] struct;
  4. Option D: struct[size] array_name;
Show answer

Answer: A. struct array_name[size];

201. In C programming, how do you access a particular member of a structure within an array of structures?

  1. Option A: array_name[index].member_name
  2. Option B: member_name.array_name[index]
  3. Option C: struct.array_name[index].member_name
  4. Option D: member_name[index].array_name
Show answer

Answer: A. array_name[index].member_name

202. What is the purpose of using an array of structures in C?

  1. Option A: To group similar data types together in a single entity.
  2. Option B: To group different data types together in a single entity.
  3. Option C: To make the code easier to read and maintain.
  4. Option D: To create a single variable that can hold multiple values.
Show answer

Answer: A. To group similar data types together in a single entity.

203. How do you initialize an array of structures in C?

  1. Option A: By setting each member of the array individually.
  2. Option B: By setting the values of the first member of the array, which automatically sets the values of the rest of the members.
  3. Option C: By using a loop to set the values of each member of the array.
  4. Option D: By using a pointer to set the values of each member of the array.
Show answer

Answer: A. By setting each member of the array individually.

204. What is the maximum number of dimensions that an array of structures can have in C?

  1. Option A: One
  2. Option B: Two
  3. Option C: Three
  4. Option D: There is no limit
Show answer

Answer: D. There is no limit

205. What is the purpose of using a typedef with an array of structures in C?

  1. Option A: To make it easier to declare variables of that type.
  2. Option B: To make the code more readable.
  3. Option C: To make it easier to access the members of the array.
  4. Option D: To create a new data type.
Show answer

Answer: D. To create a new data type.

206. Which of the following is a valid way to access a member of a structure within an array of structures in C?

  1. Option A: array_name.member_name[index]
  2. Option B: array_name[index].member_name
  3. Option C: member_name.array_name[index]
  4. Option D: struct.array_name[index].member_name
Show answer

Answer: B. array_name[index].member_name

207. How do you declare a pointer to an array of structures in C?

  1. Option A: struct *array_name[size];
  2. Option B: struct (*array_name)[size];
  3. Option C: struct *array_name[size];
  4. Option D: struct (*array_name)[size];
Show answer

Answer: B. struct (*array_name)[size]; or D. struct (*array_name)[size];

Two options have the same text; both match the source’s answer.

208. In C programming, how do you access a particular member of a structure within a pointer to an array of structures?

  1. Option A: pointer_name->member_name[index]
  2. Option B: pointer_name[index]->member_name
  3. Option C: pointer_name.member_name[index]
  4. Option D: pointer_name[index].member_name
Show answer

Answer: D. pointer_name[index].member_name

209. How do you dynamically allocate memory for an array of structures in C?

  1. Option A: By using the malloc() function.
  2. Option B: By using the calloc() function.
  3. Option C: By using the realloc() function.
  4. Option D: By using the free() function.
Show answer

Answer: A. By using the malloc() function.

210. How do you declare an array of structures in C?

  1. Option A: struct Array = {...}
  2. Option B: struct *Array = {...}
  3. Option C: struct Array[] = {...}
  4. Option D: struct Array {...}
Show answer

Answer: C. struct Array[] = {...}

211. What is the correct syntax for accessing the member variable "age" of the first structure in an array of structures named "people"?

  1. Option A: people.age[0]
  2. Option B: people[0].age
  3. Option C: people.age->0
  4. Option D: age[0].people
Show answer

Answer: B. people[0].age

212. What is the maximum number of elements that can be stored in an array of structures?

  1. Option A: There is no maximum number
  2. Option B: The maximum number is determined by the size of each element
  3. Option C: The maximum number is 1024
  4. Option D: The maximum number is determined by the amount of available memory
Show answer

Answer: D. The maximum number is determined by the amount of available memory

213. Which of the following is a valid way to initialize an array of structures in C?

  1. Option A: struct person[] = {{1, "John"}, {2, "Jane"}}
  2. Option B: struct person[] = { 1, "John" , {2, "Jane"}, {3, "Bob"}}
  3. Option C: struct person = [1] = {1, "John"}, [2]= {2, "Jane"}
  4. Option D: All of the above
Show answer

Answer: A. struct person[] = {{1, "John"}, {2, "Jane"}}

214. What is the size of the following structure? struct student { char name[50]; int age; float gpa; };

  1. Option A: 54 bytes
  2. Option B: 60 bytes
  3. Option C: 62 bytes
  4. Option D: 64 bytes
Show answer

Answer: B. 60 bytes

215. Which operator is used to access a member of a structure through a pointer to the structure?

  1. Option A: .
  2. Option B: ->
  3. Option C: *
  4. Option D: &
Show answer

Answer: B. ->

216. What is the correct syntax for declaring a pointer to a structure?

  1. Option A: struct *p;
  2. Option B: struct p;
  3. Option C: struct pointer;
  4. Option D: struct person *p;
Show answer

Answer: D. struct person *p;

217. How can you dynamically allocate memory for an array of structures in C?

  1. Option A: struct array = (struct *) malloc(sizeof(struct) * n);
  2. Option B: struct array = (struct**) malloc(n * sizeof(struct));
  3. Option C: struct array = (struct*) malloc(n);
  4. Option D: struct array = (struct*) malloc(sizeof(struct));
Show answer

Answer: A. struct array = (struct *) malloc(sizeof(struct) * n);

218. How can you access the last element in an array of structures with n elements?

  1. Option A: arr[n]
  2. Option B: arr[n-1]
  3. Option C: arr.last
  4. Option D: arr.end
Show answer

Answer: B. arr[n-1]

219. Which of the following is an advantage of using an array of structures instead of multiple individual structures?

  1. Option A: Easier to manage
  2. Option B: Easier to pass to functions
  3. Option C: Requires less memory
  4. Option D: All of the above
Show answer

Answer: D. All of the above

220. What is the syntax for passing a structure to a function in C?

  1. Option A: function(struct s)
  2. Option B: function(struct *s)
  3. Option C: function(*s)
  4. Option D: function(&s)
Show answer

Answer: A. function(struct s)

221. How do you declare a function that takes a structure as an argument in C?

  1. Option A: void myFunction(struct myStruct);
  2. Option B: void myFunction(struct myStruct *);
  3. Option C: void myFunction(*myStruct);
  4. Option D: void myFunction(&myStruct);
Show answer

Answer: A. void myFunction(struct myStruct);

222. Can you pass an array of structures to a function in C?

  1. Option A: No, C does not support passing arrays of structures to functions
  2. Option B: Yes, you can pass an array of structures to a function using a pointer
  3. Option C: Yes, you can pass an array of structures to a function by value
  4. Option D: Yes, you can pass an array of structures to a function using the & operator
Show answer

Answer: B. Yes, you can pass an array of structures to a function using a pointer

223. How does passing a structure to a function by reference (i.e. using a pointer) differ from passing it by value?

  1. Option A: Passing by reference creates a copy of the structure, while passing by value does not
  2. Option B: Passing by reference allows the function to modify the original structure, while passing by value does not
  3. Option C: Passing by reference is slower than passing by value
  4. Option D: Passing by reference is not allowed in C
Show answer

Answer: B. Passing by reference allows the function to modify the original structure, while passing by value does not

224. What is the advantage of passing a structure to a function by reference instead of by value?

  1. Option A: Passing by reference is faster
  2. Option B: Passing by reference allows the function to modify the original structure
  3. Option C: Passing by reference is easier to write
  4. Option D: Passing by reference requires less memory
Show answer

Answer: A. Passing by reference is faster

225. How do you access a structure member inside a function that takes a pointer to the structure as an argument?

  1. Option A: s.member
  2. Option B: (*s).member
  3. Option C: &s->member
  4. Option D: s->member
Show answer

Answer: D. s->member

226. What is the correct way to pass a structure to a function by reference?

  1. Option A: function(struct s)
  2. Option B: function(struct *s)
  3. Option C: function(&s)
  4. Option D: function(*s)
Show answer

Answer: C. function(&s)

227. Can a function return a structure in C?

  1. Option A: Yes, by using the & operator
  2. Option B: Yes, but it requires passing a pointer to the structure as an argument
  3. Option C: Yes, by returning a pointer to the structure
  4. Option D: No, C does not support returning structures from functions
Show answer

Answer: C. Yes, by returning a pointer to the structure

228. How do you initialize a structure variable inside a function?

  1. Option A: struct s = {...}
  2. Option B: s = {...}
  3. Option C: Pass by value
  4. Option D: Pass by reference
Show answer

Answer: A. struct s = {...}

229. What is the advantage of passing a structure by pointer to a function in C?

  1. Option A: It reduces the size of the structure
  2. Option B: It increases the speed of the program
  3. Option C: It allows the function to modify the original structure
  4. Option D: None of the above
Show answer

Answer: C. It allows the function to modify the original structure

230. Which of the following is the correct syntax to pass a structure by value to a function in C?

  1. Option A: function_name(&structure_variable)
  2. Option B: function_name(*structure_variable)
  3. Option C: function_name(structure_variable)
  4. Option D: function_name(structure_pointer)
Show answer

Answer: C. function_name(structure_variable)

231. Which of the following is the correct syntax to pass a structure by reference to a function in C?

  1. Option A: function_name(&structure_variable)
  2. Option B: function_name(*structure_variable)
  3. Option C: function_name(structure_variable)
  4. Option D: function_name(structure_pointer)
Show answer

Answer: A. function_name(&structure_variable)

232. Which of the following is the correct syntax to pass a structure by pointer to a function in C?

  1. Option A: function_name(&structure_variable)
  2. Option B: function_name(structure_variable)
  3. Option C: function_name(structure_pointer)
  4. Option D: function_name(*structure_variable)
Show answer

Answer: C. function_name(structure_pointer)

3.3 C++ language constructs with objects and classes

225 questions · ACtE0303

233. Can two functions in C++ have the same name and parameters?

  1. Option A: Yes, if different return types
  2. Option B: Yes, if in different namespaces
  3. Option C: No, not allowed
  4. Option D: Yes, if in different classes
Show hint

Namespaces provide scope separation.

Show answer

Answer: B. Yes, if in different namespaces

Functions can have same name and parameters if in different namespaces, due to namespace scope separation.

234. What is default access specifier for C++ class members?

  1. Option A: Public
  2. Option B: Protected
  3. Option C: Private
  4. Option D: None
Show hint

Unless explicitly specified otherwise.

Show answer

Answer: C. Private

By default, all class members in C++ are private unless declared as public or protected.

235. What namespace feature does C++ provide?

  1. Option A: Can be used anywhere
  2. Option B: Only within file
  3. Option C: Only within function
  4. Option D: Only within class
Show hint

Global scope feature.

Show answer

Answer: A. Can be used anywhere

Namespaces provide scope for identifiers and can be used throughout the program.

236. How to alias namespace in C++?

  1. Option A: namespace A::B
  2. Option B: using A::B
  3. Option C: namespace B = A
  4. Option D: using namespace A::B
Show hint

Create alias for namespace.

Show answer

Answer: C. namespace B = A

Correct syntax: namespace new_name = existing_namespace; creates alias.

237. What is static variable in C++?

  1. Option A: Changes on each call
  2. Option B: Persists between calls
  3. Option C: Local variable
  4. Option D: Global always
Show hint

Retains value.

Show answer

Answer: B. Persists between calls

Static variables retain their value between function calls and are initialized only once.

238. What are namespaces in C++?

  1. Option A: Memory allocation regions
  2. Option B: Scopes for declaring names to avoid conflicts
  3. Option C: Function calling mechanisms
  4. Option D: Object storage areas
Show hint

Multiple libraries might have function with same name - how do you avoid collision?

Show answer

Answer: B. Scopes for declaring names to avoid conflicts

Namespaces: organize code into logical groups, avoiding name conflicts in large projects. Declaration: namespace MyLib { function definitions, class definitions, variables }. Prevents collisions: two libraries with function calc() can coexist in different namespaces. Accessing: MyLib::calc() or using namespace MyLib; then calc(). Nested namespaces: namespace A { namespace B { class C { }; } } accessed as A::B::C. Using statement: using namespace std; brings std namespace into current scope (avoid at global scope in headers - causes pollution). Using declaration: using std::cout; imports specific identifier. Scope: identifiers in namespace not visible outside unless qualified or using declaration. Example: namespace math { int square(int x) { return x*x; } } then math::square(5) or using math::square; square(5). Standard library: std namespace contains cout, cin, vector, etc. Alias: namespace fs = std::filesystem; shortens names. Unnamed namespace: namespace { /* internal linkage */ } makes identifiers private to translation unit (internal linkage). Advantages: organize large codebases, prevent name pollution, support versioning (different lib versions in different namespaces). Best practice: put library code in namespace, avoid using namespace MyLib; at global scope. Anonymous namespaces more preferred than static for internal linkage. C doesn't have namespaces (uses module/header structure instead). Understanding namespace scope crucial for managing large C++ projects and library integration.

239. What is function overloading in C++?

  1. Option A: Calling function multiple times
  2. Option B: Multiple functions with same name but different parameters
  3. Option C: Loading function at runtime
  4. Option D: Allocating more memory to function
Show hint

Can you have multiple add() functions that work differently?

Show answer

Answer: B. Multiple functions with same name but different parameters

Function overloading: multiple functions with same name differentiated by parameter list (number, type, or order). Compiler generates unique internal names (name mangling) for each version. Examples: int add(int a, int b) { return a+b; } and double add(double a, double b) { return a+b; } and string add(string a, string b) { return a+b; }. Selection: compiler chooses based on argument types: add(3, 5) calls int version, add(3.5, 2.1) calls double version. Rules: (1) Parameter count must differ or parameter types different. (2) Return type alone insufficient (can't overload on return type only). (3) const qualifier on parameters: const int* vs int* treated as different. Parameter order matters: void foo(int, double) differs from void foo(double, int). Coercion: compiler tries implicit conversions if exact match not found. Ambiguity: foo(5, 5) could match foo(int, int) or foo(double, double) if implicit conversion possible - compiler rejects as ambiguous. Default parameters: foo(int a, int b = 0) with foo(int) allows calling with one argument. Advantages: same operation, intuitive interface (add works for int, double, string), cleaner code. Disadvantages: debugging harder (which version called?), compile-time complexity, risk of ambiguity. Prefix/postfix operators: operator++ can be overloaded as prefix vs postfix using dummy int parameter. Virtual functions: overloading differs from overriding (inheritance). Can combine overloading with inheritance. Modern practice: favor overloading for related operations, templates for generic code. Understanding overloading essential for C++ API design and avoiding errors.

240. What are inline functions in C++?

  1. Option A: Functions written within single line
  2. Option B: Functions expanding at call site to improve performance
  3. Option C: Functions without implementation
  4. Option D: Functions called repeatedly
Show hint

Compiler optimization that replaces function call with function body.

Show answer

Answer: B. Functions expanding at call site to improve performance

Inline functions: compiler replaces function call with function body directly, eliminating function call overhead (parameter passing, stack frame creation, return). Declaration: inline return_type function_name(parameters) { body }; Implicit inline: member functions defined in class body automatically inline. Advantages: eliminates call overhead (beneficial for small functions called frequently), enables compiler optimizations, can be faster than macros (type-safe). Disadvantages: code size increase (body duplicated at each call site), compilation slower, not suitable for large functions, implementation visible to users (header files), can't recurse. When beneficial: small functions (1-3 lines) called frequently (loops, callbacks). When inefficient: large functions, recursive functions, functions called rarely. Compiler discretion: inline is hint, compiler may ignore for complex functions. Modern practice: compiler often makes inlining decisions better than hints. Rule of thumb: let compiler decide (don't use inline keyword unless profiling shows benefit). Template functions: implicitly inline (needed in header files). Lambda functions: automatically inline. Recursive inline: compiler typically expands limited times. Virtual functions: virtual prevents inlining (runtime dispatch). Debugging: inlined functions harder to debug (breakpoints, stepping). Performance profiling: measure before optimizing with inline. Example: inline int square(int x) { return x*x; } called 1000 times avoids 1000 function call overheads. Understanding inlining crucial for performance tuning without sacrificing code organization.

241. What are default arguments in C++ functions?

  1. Option A: Arguments passed when calling function
  2. Option B: Parameter values used if argument not provided
  3. Option C: Values stored in function memory
  4. Option D: Required parameters in function
Show hint

void func(int x = 5) - what happens if you call func() without arguments?

Show answer

Answer: B. Parameter values used if argument not provided

Default arguments: parameter values used when argument not provided in function call. Declaration: int multiply(int a, int b = 2) { return a * b; }. Call: multiply(5) uses b=2, multiply(5, 3) uses b=3. Rules: (1) defaults must be rightmost parameters - int func(int a = 1, int b) invalid; (2) only in declaration, not definition (usually); (3) can be expression not just constant: int func(int a = getDefault()). Examples: cout << setprecision(6) uses default, file open with default permissions. Multiple defaults: int func(int a = 1, int b = 2, int c = 3) all have defaults, can omit from right. Partial defaults: int func(int a, int b = 2) requires first argument, second optional. Benefits: backward compatibility (add parameters with defaults to existing functions), reduce function overloading, cleaner API (optional parameters). Drawbacks: can make code less clear (hidden parameters), debugging harder (which version called?), difficult with function pointers. Overloading vs defaults: func(int) and func(int, int) as overloads vs func(int, int = 0) as defaults both valid, different trade-offs. Variadic functions: alternative to defaults for variable arguments. Template defaults: template<typename T = int> class MyClass. Constructor defaults: MyClass(int size = 10) { }. Common pattern: void init(string name = "", int value = 0, bool flag = false). Understanding defaults improves API design and reduces verbosity.

242. What does pass by reference mean in C++?

  1. Option A: Passing memory address to function
  2. Option B: Parameter becomes alias to original variable
  3. Option C: Copying variable value to function
  4. Option D: Passing pointer to function
Show hint

int& ref vs int* ptr - what's the difference in usage?

Show answer

Answer: B. Parameter becomes alias to original variable

Pass by reference: parameter becomes alias (alternative name) to original variable, not separate copy. Declaration: void swap(int& a, int& b) { int t=a; a=b; b=t; }. Usage: int x=5, y=10; swap(x, y) modifies x and y directly. Differences from pointer: reference cannot be null, cannot rebind, syntactically cleaner (no dereferencing). Reference characteristics: (1) must be initialized at declaration. (2) bound to same variable throughout lifetime. (3) syntactically like original variable (no * or ->). (4) compiler implements via pointers internally. Const reference: const int& ref prevents modification through reference. Example: void print(const string& s) { cout << s; } avoids string copy. Return by reference: int& get_ref() { return value; }; must return valid reference (not local variable). Use: minimize copying for large objects. Advantages: cleaner syntax than pointers, efficient (no copy), prevents accidental null. Disadvantages: const reference can extend lifetime of temporaries (returns reference to temporary valid while reference exists). Reference vs pointer: both achieve same at assembly level, references safer (no null), pointers more flexible (rebindable). Array references: int (&arr)[10] reference to 10-element array. Function references: int (&func)() reference to function returning int. Forward reference: forward declare class for reference members. Common pattern: template<typename T> void swap(T& a, T& b) works with any type. Rvalue reference: int&& rvalue_ref moves semantics. Understanding references crucial for modern C++ and efficient coding.

243. What is a class in C++?

  1. Option A: Syntax for declaring variables
  2. Option B: User-defined data type containing data members and member functions
  3. Option C: Derived type from struct
  4. Option D: Memory allocation mechanism
Show hint

Think of class as blueprint combining data and operations on that data.

Show answer

Answer: B. User-defined data type containing data members and member functions

Class: user-defined type bundling data (member variables) and functions (methods) operating on data, encapsulating state and behavior. Declaration: class ClassName { public: data members, methods; private: data members, methods; }. Object: instance of class, created on stack/heap. Example: class Student { private: int id; string name; public: void setId(int i) { id = i; } int getId() { return id; } }. Key differences from struct: default access private (struct default public). Encapsulation: hide implementation details, expose interface. Inheritance: class derived : public base { }; enables code reuse. Polymorphism: virtual functions enable runtime dispatch. Abstraction: present high-level interface, hide complexity. Composition: class contains other classes. Member initialization: in constructor. Static members: shared by all instances. Friend: external function accessing private data. Constructor: initializes object state. Destructor: cleans up resources. Access specifiers: public (anyone), protected (derived classes), private (only class). This pointer: refers to current object. Const member functions: const void display() { } don't modify state. Mutable: fields modified in const functions. Example uses: Point (x, y coordinates), Bank Account (balance, transactions), Game Character (health, inventory). Objects in memory: each instance has own member variables, shared method code. Understanding classes fundamental to OOP and modern C++ design.

244. What are access specifiers in C++ classes?

  1. Option A: Keywords defining variable types
  2. Option B: Controls visibility and accessibility of class members
  3. Option C: Parameters in function calls
  4. Option D: Memory allocation directives
Show hint

public, private, protected - what do they control?

Show answer

Answer: B. Controls visibility and accessibility of class members

Access specifiers: control member visibility and accessibility. Three levels: (1) public: accessible from anywhere (outside class, derived classes). (2) private: accessible only within class (not derived classes or outside). (3) protected: accessible within class and derived classes, not outside. Default: class has private default (struct has public). Example: class MyClass { private: int secret; public: void setSecret(int s) { secret = s; } int getSecret() { return secret; } }; secret accessible only through public methods. Encapsulation: hide internal state (private), expose interface (public). Benefits: control access, validate data (setters can check), change implementation without breaking API. Derived classes: inherit all members, but private members inaccessible (even through inheritance), protected members accessible. Friend classes: friend class OtherClass allows OtherClass accessing private members (breaks encapsulation, use carefully). Friend functions: friend void func() accesses private. Const objects: only const member functions callable. Static: class-level members, shared by all instances. Example architecture: class BankAccount { private: double balance; public: void deposit(double amount) { if(amount > 0) balance += amount; } }. Getters/setters: data hiding pattern (getSalary(), setSalary(val)). Inheritance: class Derived : private Base (inherits all as private by default), : public Base (inherits public as public). Understanding access control essential for data protection and maintainability.

245. What are member functions in C++?

  1. Option A: Functions that operate on class members
  2. Option B: Functions outside class using member data
  3. Option C: Member variables of function type
  4. Option D: Functions in multiple classes
Show hint

Methods defined inside class definition - what do they do with data members?

Show answer

Answer: A. Functions that operate on class members

Member functions (methods): functions defined within class, operating on class data members. Declaration: class Circle { private: double radius; public: void setRadius(double r) { radius = r; } double getArea() { return 3.14 * radius * radius; } }. Implicit this pointer: member functions have hidden 'this' parameter (pointer to object). Example: setRadius(5) becomes setRadius(&object, 5) internally. Accessing members: direct access (radius = r) without this-> (implicit). Const member functions: void display() const { /* read-only */ } cannot modify members. Mutable members: modified even in const functions. Static member functions: static void staticFunc() { } no 'this' pointer, access only static members. Virtual functions: virtual void func() { } enabling polymorphism. Inline definition: defined in class body, implicitly inline. Separate definition: void MyClass::func() { } defined outside class. Example: class List { private: vector<int> data; public: void add(int val) { data.push_back(val); } int size() { return data.size(); } void display() { for(int x : data) cout << x; } }. Friend: non-member function accessing private data. Operator overloading: member functions for operators (+, [], (), etc.). Constructors/destructors: special member functions. Getters: return member values. Setters: modify members with validation. Callbacks: function pointers, functors, lambdas. Understanding member functions crucial for OOP design and encapsulation.

246. What are constructors in C++?

  1. Option A: Functions that construct buildings
  2. Option B: Special functions initializing object state
  3. Option C: Functions building classes
  4. Option D: Compiler directives
Show hint

Called automatically when object created - what does it do?

Show answer

Answer: B. Special functions initializing object state

Constructor: special member function automatically called when object created, initializing member variables. Characteristics: (1) Same name as class. (2) No return type. (3) Can be overloaded. (4) Automatically called (cannot call explicitly except with new). Types: Default constructor (no parameters): MyClass() { }. Parameterized constructor: MyClass(int id, string name) { this->id=id; this->name=name; }. Copy constructor: MyClass(const MyClass& obj) { /* copy members */ }. Move constructor: MyClass(MyClass&& obj) { /* move members */ }. Initialization list: MyClass(int x) : id(x), name("") { } initializes before body. Delegating: MyClass() : MyClass(0, "") { } calls another constructor. Example: class Person { private: string name; int age; public: Person() { name=""; age=0; } Person(string n, int a) { name=n; age=a; } Person(const Person& p) { name=p.name; age=p.age; } }. Default initialization: Person p creates object with default constructor. Explicit: explicit MyClass(int) prevents implicit conversion. Deleted: MyClass(const MyClass&) = delete; prevents copying. Default: MyClass(const MyClass&) = default; compiler-generated copy. Base class constructor: Derived() : Base(args) { }. Advantages: guaranteed initialization, can validate input. Disadvantages: complex with inheritance, rule of five (constructor, destructor, copy constructor, copy assignment, move constructor/assignment). Best practice: define all constructors explicitly or =default/=delete. Understanding constructors essential for object lifecycle management.

247. What are destructors in C++?

  1. Option A: Functions that destroy objects
  2. Option B: Special functions cleaning up resources when object destroyed
  3. Option C: Functions removing class members
  4. Option D: Operators for object deletion
Show hint

Called automatically when object lifetime ends - releases allocated resources.

Show answer

Answer: B. Special functions cleaning up resources when object destroyed

Destructor: special member function automatically called when object destroyed, cleaning up resources. Characteristics: (1) Tilde (~) prefix: ~MyClass() { }. (2) No parameters, no return type. (3) Cannot be overloaded. (4) Automatically called (stack objects on scope exit, heap objects with delete). Purpose: release dynamically allocated memory, close files, release locks, cleanup resources. Example: class File { private: FILE* handle; public: File(string path) { handle=fopen(path.c_str(), "r"); } ~File() { if(handle) fclose(handle); } }. Virtual destructor: virtual ~MyClass() { } necessary for polymorphic classes (derived class cleanup called). No cleanup needed: if all members managed (string, vector), compiler-generated destructor sufficient. Delete: object *obj = new object(); delete obj; calls destructor before freeing memory. Smart pointers: unique_ptr, shared_ptr automatically call destructor (RAII pattern). Copy and swap: MyClass& operator=(const MyClass& other) { MyClass temp(other); swap(*this, temp); return *this; }. Exception safety: destructors shouldn't throw (undefined behavior). Resource acquisition is initialization (RAII): constructor acquires, destructor releases. Rule of five: if defining destructor, usually need copy constructor, copy assignment, move constructor, move assignment. Example: class Database { private: Connection* conn; public: ~Database() { if(conn) conn->close(); } }. Understanding destructors crucial for resource management and preventing leaks.

248. What is dynamic memory allocation for objects in C++?

  1. Option A: Creating objects at compile time
  2. Option B: Using new/delete operators to allocate/deallocate memory on heap
  3. Option C: Automatically allocating memory
  4. Option D: Allocating fixed memory amounts
Show hint

MyClass* obj = new MyClass() creates object where? How to destroy?

Show answer

Answer: B. Using new/delete operators to allocate/deallocate memory on heap

Dynamic allocation: creating objects on heap at runtime using new, deallocating with delete. Syntax: MyClass *ptr = new MyClass(); destroys with delete ptr; Stack vs Heap: stack (limited, automatic cleanup), heap (larger, manual management). Object creation: new MyClass() calls constructor, returns pointer. Example: class Point { public: Point(int x, int y) { /* init */ } }; Point *p = new Point(3, 4); creates object on heap. Deallocation: delete p; calls destructor, frees memory. Array allocation: MyClass *arr = new MyClass[10]; delete[] arr; (note: delete[] for arrays). Constructor called: new calls constructor for each element. Destructor called: delete/delete[] calls destructor before freeing. Null check: always verify new didn't fail (though modern C++ throws bad_alloc on failure). Memory leak: forgetting delete causes memory leak (allocated memory never freed). Dangling pointer: using pointer after delete causes undefined behavior. Smart pointers: unique_ptr<MyClass> auto-deletes when out of scope (preferred modern approach). Example: unique_ptr<MyClass> obj(new MyClass()); no explicit delete needed. Advantages dynamic: flexible size, allocate/deallocate as needed, build complex structures. Disadvantages: manual management error-prone, performance slower than stack, fragmentation risk. Exception safety: if exception thrown after new but before assignment, memory leaks. Solution: smart pointers. Variably-sized objects: arrays of user-determined size (not possible on stack with fixed size). Custom allocators: overload new/delete for specialized allocation. Understanding dynamic allocation essential for building flexible data structures.

249. What is the this pointer in C++?

  1. Option A: Pointer to current function
  2. Option B: Pointer to current object within member function
  3. Option C: Pointer to class definition
  4. Option D: Pointer declared with this keyword
Show hint

In member function, how do you refer to current object? Is it implicit or explicit?

Show answer

Answer: B. Pointer to current object within member function

This pointer: implicit pointer to object on which member function operates. Implicit: compiler adds automatically, usually invisible. Usage: accessing ambiguous members: class MyClass { int x; void setX(int x) { this->x = x; } }. Explicit use: returning self reference: MyClass& getThis() { return *this; }. Chaining: MyClass& setValue(int v) { value=v; return *this; } enables obj.setValue(5).display(). Accessing members: this->member equivalent to member in same context. Non-member functions: no 'this' (static member functions, free functions). Const member: void func() const { // this is const MyClass* this } - points to const object. Non-const member: void func() { // this is MyClass* this }. Using explicitly: method operators -> in recursive structures. Comparison: if(this == &obj) checks if operating on same object. Example: class List { void append(List& other) { if(this == &other) return; /* avoid self-append */ } }. Implementing swap: void swap(MyClass& other) { swap(*this, other); }. Self-assignment check: operator= check avoids issues. Address passing: methods receiving own object via this pointer. Memory: 'this' stored in register for efficiency, not additional memory per object. Cannot modify: 'this' is const pointer, cannot make point to different object. Smart use: returning *this in assignment operators, chaining operations, self-reference checks. Understanding 'this' crucial for method implementation and operator overloading.

250. What are static data members in C++?

  1. Option A: Data members allocated on stack
  2. Option B: Class-level variables shared by all instances
  3. Option C: Immutable data members
  4. Option D: Data members constant throughout program
Show hint

Data belonging to class, not individual objects - shared by all instances.

Show answer

Answer: B. Class-level variables shared by all instances

Static data members: variables shared by all class instances, storage at class level not object level. Declaration: class Counter { static int count; public: Counter() { count++; } }. Definition outside: int Counter::count = 0; (must be defined outside class). Access: Counter::count accesses from class, obj.count from object (not recommended). Characteristics: (1) Shared by all instances. (2) Initialized once. (3) Lifetime extends entire program. (4) Default-initialized to zero. Uses: counters (count instances), configuration (shared settings), caches. Example: class MyClass { private: static int instances; public: MyClass() { instances++; } static int getInstances() { return instances; } }. Static member function: static void staticFunc() { } no 'this', access only static members. Mutable static: static int value can be modified in const member functions if mutable. Thread safety: static initialization thread-safe (C++11), but access not thread-safe (need locks). Const static: static const int MAX = 100; compile-time constant. Constexpr: constexpr static int VALUE = 42; (C++17, can be used in compile-time expressions). Disadvantages: global state (complicates testing, hidden dependencies), thread-safety issues. Testing: difficult with static members (persist across tests). Workaround: reset in constructor/destructor or friend test classes. Design consideration: prefer instance members when possible, use static only when truly class-level. Singleton pattern: static instance of class. Understanding static members essential for resource management and class-level state.

251. What are constant member functions in C++?

  1. Option A: Functions with constant parameters
  2. Option B: Functions that don't modify object state
  3. Option C: Functions returning constants
  4. Option D: Functions with const return type
Show hint

void func() const - what does const at end mean?

Show answer

Answer: B. Functions that don't modify object state

Const member functions: methods that don't modify object state, 'this' pointer becomes const pointer to const. Declaration: int getValue() const { return value; }. Guarantee: compiler prevents accidental modifications. Example: class Vector { private: double x, y; public: double length() const { return sqrt(x*x + y*y); } void scale(double factor) { x *= factor; y *= factor; } }; length() const, scale() non-const. Benefits: (1) Intent clarity (read-only operation). (2) Compiler enforcement. (3) Callable on const objects. (4) Callable on const references. Const objects: const Vector v(3, 4); can only call const methods. Const reference: void display(const Vector& v) can pass any Vector, calls const methods. Mutable members: mutable int cache_value can be modified in const methods (for caching). Example: class Square { private: double side; mutable double cached_area; public: double area() const { cached_area = side*side; return cached_area; } }. Overloading on const: can have both const and non-const versions. Example: class Container { public: int& operator[](int i) { return data[i]; } const int& operator[](int i) const { return data[i]; } }. Const correctness: best practice to mark all non-modifying functions const. Volatile: volatile methods for hardware variables. Thread-safety: const doesn't guarantee thread-safety (only single-thread). Bitwise vs logical: compiler enforces bitwise const (not logical const with mutable). Practice: use const liberally for safer, more maintainable code. Understanding const member functions crucial for API design and correctness.

252. What are friend functions and classes in C++?

  1. Option A: Functions that are friends of other functions
  2. Option B: External functions/classes granted access to private members
  3. Option C: Classes that inherit from each other
  4. Option D: Mutually dependent classes
Show hint

How can non-member function access private class data?

Show answer

Answer: B. External functions/classes granted access to private members

Friend: mechanism allowing non-member function or another class to access private/protected members. Friend function: friend ostream& operator<<(ostream& os, const MyClass& obj) { os << obj.private_data; return os; }. Usage: declared inside class, defined outside. Not member function: not inherited, no 'this' pointer. Example: class Complex { private: double real, imag; friend Complex add(Complex a, Complex b); }; add() can access real and imag. Friend class: friend class OtherClass allows OtherClass all access. Declaration: friend class OtherClass inside MyClass. Uses: (1) Operator overloading (<<, >>, stream operators). (2) Utility functions. (3) Related classes (iterator with container). Advantages: non-member function can access private (cleaner for operators). Disadvantages: breaks encapsulation, creates coupling. Bidirectional: friendship not inherited, one-way (A friend of B, doesn't make B friend of A). Scope: friend declared in class but not member, defined outside like free function. Best practice: minimize friends, prefer accessors when possible. Example: nested class (has natural access): class Outer { private: int data; class Inner { Outer& outer; }; }. Forward declaration: friend class Forward; (class Forward not yet defined). Iterator pattern: friend allows iterator accessing container's private members. Testing: friend often used for unit testing (test class as friend). Understanding friends crucial for operator overloading and library design.

253. Which access specifier is used to make the members of a class accessible only within the same class?

NEC model set
  1. Option A: public
  2. Option B: private
  3. Option C: protected
  4. Option D: public and protected
Show hint

Private members cannot be accessed from outside the class or even from derived classes.

Show answer

Answer: B. private

The 'private' access specifier restricts access to class members strictly to within the same class only. Private members: (1) Cannot be accessed from outside the class, (2) Cannot be accessed from derived classes, (3) Cannot be accessed by friend functions (unless explicitly declared as friends), (4) Provide encapsulation and data hiding. Public members are accessible from anywhere. Protected members are accessible within the class and derived classes. The private specifier is fundamental to object-oriented programming's encapsulation principle - hiding internal implementation details. For example: class MyClass { private: int x; // Only accessible within MyClass }; Attempting to access private members from outside the class results in compilation errors. This enforces data abstraction and prevents unintended modifications to internal state.

254. How is a friend function declared inside a class?

NEC model set
  1. Option A: By using the keyword friend before the function declaration
  2. Option B: By defining the function inside the class without friend keyword
  3. Option C: By declaring the function as public
  4. Option D: By declaring the function as private
Show hint

The 'friend' keyword grants access to private/protected members.

Show answer

Answer: A. By using the keyword friend before the function declaration

A friend function is declared inside a class by using the keyword 'friend' before the function declaration. Friend function concept: (1) Non-member function declared as friend inside class, (2) Has access to private/protected members, (3) NOT a member function - No this pointer, (4) Breaks encapsulation (intentionally). Friend function declaration: friend void externalFunction(ClassName obj);, friend class OtherClass;. Characteristics: (1) Declared inside class with 'friend' keyword, (2) Implemented outside class - No scope resolution operator needed, (3) Can access private/protected members, (4) Not inherited - Friends of base not friends of derived. Difference from member functions: (1) Member functions - Have this pointer, part of class, (2) Friend functions - No this pointer, external to class, (3) Operator overloading - Both can be friends. Usage example: class MyClass { private: int value; friend void setMyClass(MyClass &obj, int val); }; void setMyClass(MyClass &obj, int val) { obj.value = val; // Allowed!}. When needed: (1) Operator overloading - <<, >> operators, (2) Binary operators - Need access to both objects, (3) Tight coupling desired - Controlled access, (4) Symmetric operations - Same access needed. Operator example: ostream& operator<<(ostream &out, MyClass obj) { return out << obj.value; }. Limitations: (1) Breaks encapsulation - Use carefully, (2) Not inherited - Must re-declare in subclass, (3) No virtual friends - Can't override, (4) Unidirectional - Class A makes B friend, B doesn't get A access. Modern practice: (1) Minimize friend declarations, (2) Prefer member functions when possible, (3) Friend classes - Tighter coupling alternative, (4) API design - Consider implications. This provides controlled access beyond standard encapsulation.

255. Which of the following statements is true about static functions?

Past question
  1. Option A: Static functions can be overloaded
  2. Option B: Static functions are implicit
  3. Option C: Static functions can be overloaded when derived from a base class
  4. Option D: Static functions cannot be overloaded
Show hint

Static functions belong to the class, not to instances. Can you have multiple static functions with the same name?

Show answer

Answer: A. Static functions can be overloaded

Static functions can be overloaded. This is a fundamental C++ concept. Understanding Static Functions: (1) Static functions belong to the class, not to objects, (2) Called using ClassName::functionName(), (3) Can access only static data members, (4) Do not have 'this' pointer. Overloading Rules: (1) Overloading requires different parameter lists, (2) Same function name, different parameters allowed, (3) Works for both member and static functions, (4) Return type alone doesn't distinguish overloads. Static Function Overloading Example: class MyClass { public: static void display(int x); static void display(double x); static void display(int x, int y); }; All three are valid overloads of 'display'. Why Overloading Works for Static: (1) Compiler can distinguish by parameter types, (2) Does not violate static function properties, (3) No polymorphism issue, (4) Compile-time binding still applies. Static vs Non-Static Overloading: (1) Both can be overloaded in same class, (2) Static version called on class, (3) Non-static version called on object. Why Other Options Are Wrong: (1) Option B 'implicit' - Static functions are explicit, (2) Option C - Cannot override static functions in derived class (hiding, not overriding), (3) Option D - Contradicts correct answer. Common Misconceptions: (1) Static functions cannot be overloaded - FALSE, (2) Virtual static functions - Not possible (C++ rule), (3) Hiding vs Overriding - Static functions hide, not override. Practical Examples: (1) Math.max(int, int) vs Math.max(double, double), (2) Utility functions with type variations, (3) Factory methods with different parameters. This demonstrates static method design in C++.

256. Which access specifier allows members to be accessible within the same class and child classes?

Recalled from Jan 2026 exam
  1. Option A: Public
  2. Option B: Private
  3. Option C: Protected
  4. Option D: Internal
Show hint

This access specifier is more restrictive than public but allows access in derived classes. What is it?

Show answer

Answer: C. Protected

Protected is the access specifier that allows members to be accessible within the same class and child classes (derived classes). Members declared as protected cannot be accessed from outside the class or its derived classes, making them more restrictive than public but more permissive than private. This is crucial for inheritance because it allows base classes to provide implementation details to derived classes without exposing them to the outside world. Protected members are often used for implementation details that subclasses need to override or use.

257. Which object-oriented programming (OOP) concept involves bundling data and methods within a single class to protect them from outside interference?

Recalled from Jan 2026 exam
  1. Option A: Polymorphism
  2. Option B: Inheritance
  3. Option C: Encapsulation
  4. Option D: Abstraction
Show hint

Bundling data and methods together for protection. What is this concept?

Show answer

Answer: C. Encapsulation

Encapsulation is the OOP concept that involves bundling data and methods within a single class to protect them from outside interference. Encapsulation uses access specifiers (public, private, protected) to control what's accessible from outside the class. This hides internal implementation details and prevents unintended modification of object state. Encapsulation promotes data hiding and provides a controlled interface (public methods) for interacting with objects. Polymorphism deals with multiple forms. Inheritance deals with parent-child relationships. Abstraction deals with hiding complexity.

258. Which of the following statements is true about static functions in C++?

Recalled from Jan 2026 exam
  1. Option A: Static functions can be overloaded
  2. Option B: Static functions cannot be overloaded
  3. Option C: Static functions are implicitly virtual
  4. Option D: Static functions can access instance variables
Show hint

Static functions belong to the class, not instances. Can they be overloaded?

Show answer

Answer: B. Static functions cannot be overloaded

Static functions cannot be overloaded in C++. Since static functions belong to the class itself rather than instances, function resolution is based on the class and function name alone. Without instance information, the compiler cannot distinguish between overloaded static functions based on parameter types alone in all contexts. Non-static functions can be overloaded within a class hierarchy through polymorphism. Static functions cannot be virtual because they're not polymorphic. Static functions cannot access instance variables because they don't have an instance context.

259. In a structure, what is the default visibility of its members?

  1. Option A: Private
  2. Option B: Public
  3. Option C: Protected
  4. Option D: None of the above
Show answer

Answer: B. Public

260. What is a namespace in C++?

  1. Option A: It is a block of code that is used to group related variables and functions
  2. Option B: It is a feature that allows a class to inherit from multiple base classes
  3. Option C: It is a mechanism for managing the scope of identifiers in large programs
  4. Option D: It is a type of loop in C++
Show answer

Answer: C. It is a mechanism for managing the scope of identifiers in large programs

261. Which keyword is used to define a namespace in C++?

  1. Option A: namespace
  2. Option B: define
  3. Option C: namespace scope
  4. Option D: using namespace
Show answer

Answer: A. namespace

262. Which of the following statements is true regarding namespaces in C++?

  1. Option A: You can have multiple namespaces with the same name in the same program
  2. Option B: Namespaces can only contain function declarations
  3. Option C: You can define a namespace within a function
  4. Option D: The contents of a namespace can be accessed using the dot operator
Show answer

Answer: A. You can have multiple namespaces with the same name in the same program

263. What is the purpose of using the using keyword with namespaces in C++?

  1. Option A: To create an alias for a namespace
  2. Option B: To bring all the members of a namespace into the current scope
  3. Option C: To hide certain members of a namespace
  4. Option D: To define a new namespace within an existing namespace
Show answer

Answer: B. To bring all the members of a namespace into the current scope

264. What is the scope resolution operator in C++?

  1. Option A: :
  2. Option B: ::
  3. Option C: ->
  4. Option D: #
Show answer

Answer: B. ::

265. Which of the following is true regarding the scope resolution operator in C++?

  1. Option A: It is used to access the members of a namespace
  2. Option B: It is used to access the members of a class
  3. Option C: It is used to access the elements of an array
  4. Option D: It is used to access the elements of a linked list
Show answer

Answer: A. It is used to access the members of a namespace

266. What is the purpose of the unnamed namespace in C++?

  1. Option A: To make a function or variable global
  2. Option B: To limit the visibility of a function or variable to a single source file
  3. Option C: To create a new namespace within an existing namespace
  4. Option D: To create a namespace with a name that cannot be accessed by the user
Show answer

Answer: B. To limit the visibility of a function or variable to a single source file

267. Which of the following is a benefit of using namespaces in C++?

  1. Option A: They prevent naming conflicts between classes
  2. Option B: They allow you to define variables with the same name in different functions
  3. Option C: They improve the performance of the program
  4. Option D: They allow you to define variables with the same name in the same scope
Show answer

Answer: A. They prevent naming conflicts between classes

268. Which of the following is a disadvantage of using namespaces in C++?

  1. Option A: They can make the code more difficult to read and understand
  2. Option B: They increase the size of the executable file
  3. Option C: They make it more difficult to reuse code in different projects
  4. Option D: They increase the likelihood of naming conflicts between classes
Show answer

Answer: A. They can make the code more difficult to read and understand

269. Which of the following is true regarding the global namespace in C++?

  1. Option A: All variables and functions defined outside of a namespace belong to the global namespace
  2. Option B: The global namespace is automatically included in every program
  3. Option C: The global namespace can be used to define variables and functions that can be accessed from any part of the program
  4. Option D: All of the above
Show answer

Answer: D. All of the above

270. What is a namespace in C++?

  1. Option A: A container that holds a group of related variables and functions
  2. Option B: A type of loop that iterates over a collection of elements
  3. Option C: A method of creating a new object from an existing object
  4. Option D: A way to specify the data type of a variable
Show answer

Answer: A. A container that holds a group of related variables and functions

271. Which keyword is used to define a namespace in C++?

  1. Option A: using
  2. Option B: namespace
  3. Option C: define
  4. Option D: typedef
Show answer

Answer: B. namespace

272. Which of the following statements is true regarding namespaces in C++?

  1. Option A: Nested namespaces are not allowed
  2. Option B: A namespace can only contain functions
  3. Option C: Namespaces are only used in object-oriented programming
  4. Option D: Namespace members are accessed using the :: operator
Show answer

Answer: D. Namespace members are accessed using the :: operator

273. What is the purpose of using a namespace in C++?

  1. Option A: To avoid naming conflicts between variables and functions
  2. Option B: To allocate memory dynamically
  3. Option C: To overload operators for a class
  4. Option D: To declare a global variable
Show answer

Answer: A. To avoid naming conflicts between variables and functions

274. What is the default namespace in C++?

  1. Option A: std
  2. Option B: default
  3. Option C: main
  4. Option D: none of the above
Show answer

Answer: A. std

275. Can a namespace be defined across multiple files in C++?

  1. Option A: Yes, by using the using directive
  2. Option B: Yes, by using the namespace keyword
  3. Option C: No, a namespace must be defined in a single file
  4. Option D: No, a namespace can only be defined within a function
Show answer

Answer: B. Yes, by using the namespace keyword

276. Which of the following is a valid way to alias a namespace in C++?

  1. Option A: namespace A::B
  2. Option B: using A::B
  3. Option C: namespace B = A
  4. Option D: using namespace A::B
Show answer

Answer: C. namespace B = A

277. Which of the following is an advantage of using namespaces in C++?

  1. Option A: They allow for faster program execution
  2. Option B: They make it easier to reuse code
  3. Option C: They help to reduce the size of the program
  4. Option D: They prevent type conversion errors
Show answer

Answer: B. They make it easier to reuse code

278. Which of the following is true regarding the scope of a namespace in C++?

  1. Option A: A namespace can be used anywhere in the program
  2. Option B: A namespace can only be used within the file it is defined in
  3. Option C: A namespace can only be used within the class it is defined in
  4. Option D: A namespace can only be used within the function it is defined in
Show answer

Answer: A. A namespace can be used anywhere in the program

279. Which of the following statements is true about function overloading in C++?

  1. Option A: Only the function name should be the same for overloaded functions
  2. Option B: Overloaded functions can differ in the number of parameters
  3. Option C: Overloaded functions cannot have the same return type
  4. Option D: All of the above
Show answer

Answer: B. Overloaded functions can differ in the number of parameters

280. Which of the following is not a valid way of differentiating between overloaded functions?

  1. Option A: Number of parameters
  2. Option B: Order of parameters
  3. Option C: Return type
  4. Option D: None of the above
Show answer

Answer: C. Return type

281. Which of the following statements is true about function overloading in C++? (Repeated concept)

  1. Option A: Overloaded functions must have the same access level
  2. Option B: Access levels do not affect function overloading
  3. Option C: Overloaded functions must have different access levels
  4. Option D: None of the above
Show answer

Answer: B. Access levels do not affect function overloading

282. What is the benefit of function overloading in C++?

  1. Option A: It reduces the number of functions in a program
  2. Option B: It makes the code easier to read and understand
  3. Option C: It allows the same function name to be used for different operations
  4. Option D: All of the above
Show answer

Answer: C. It allows the same function name to be used for different operations

283. Which of the following is true about function overloading? (Repeated concept)

  1. Option A: Overloaded functions can have different names
  2. Option B: Overloaded functions can have the same number and types of parameters
  3. Option C: Overloaded functions must have the same return type
  4. Option D: None of the above
Show answer

Answer: D. None of the above

284. Which of the following is an example of function overloading in C++?

  1. Option A: int add(int a, int b)
  2. Option B: float add(float a, float b)
  3. Option C: void add(int a, int b)
  4. Option D: All of the above
Show answer

Answer: D. All of the above

285. What is function overloading in C++?

  1. Option A: Defining a function with the same name and same parameters as an existing function
  2. Option B: Defining a function with the same name but different parameters as an existing function
  3. Option C: Defining a function with a different name but the same parameters as an existing function
  4. Option D: Defining a function with a different name and different parameters as an existing function
Show answer

Answer: B. Defining a function with the same name but different parameters as an existing function

286. Which of the following is not a valid way to overload a function in C++?

  1. Option A: Changing the number of parameters in the function
  2. Option B: Changing the return type of the function
  3. Option C: Changing the order of the parameters in the function
  4. Option D: Changing the type of the parameters in the function
Show answer

Answer: B. Changing the return type of the function

287. What is the purpose of function overloading in C++?

  1. Option A: To create new functions with different names
  2. Option B: To create functions that have different return types
  3. Option C: To allow functions to work with different types of data
  4. Option D: To allow functions to be used with different sets of parameters
Show answer

Answer: D. To allow functions to be used with different sets of parameters

288. Which of the following is an example of function overloading in C++? (Repeated concept)

  1. Option A: int add(int x, int y)
  2. Option B: float add(float x, float y)
  3. Option C: char add(char x, char y)
  4. Option D: All of the above
Show answer

Answer: D. All of the above

289. Can two functions in C++ have the same name and the same set of parameters?

  1. Option A: Yes, as long as they have different return types
  2. Option B: Yes, as long as they are declared in different namespaces
  3. Option C: No, it is not allowed in C++
  4. Option D: Yes, as long as they are declared in different classes
Show answer

Answer: C. No, it is not allowed in C++

290. Which of the following is true about function overloading in C++? (Repeated concept)

  1. Option A: Overloaded functions must have the same name
  2. Option B: Overloaded functions must have different return types
  3. Option C: Overloaded functions must have the same number of parameters
  4. Option D: Overloaded functions must have different parameter types or different number of parameters
Show answer

Answer: D. Overloaded functions must have different parameter types or different number of parameters

291. What is the benefit of using function overloading in C++?

  1. Option A: It allows you to create functions with different names
  2. Option B: It allows you to create functions with different return types
  3. Option C: It allows you to write more efficient code
  4. Option D: It allows you to create more versatile functions
Show answer

Answer: D. It allows you to create more versatile functions

292. Can you overload a member function in C++?

  1. Option A: Yes, you can overload both member and non-member functions in C++
  2. Option B: No, member functions cannot be overloaded in C++
  3. Option C: Yes, but only if the functions have different return types
  4. Option D: Yes, but only if the functions have different parameters
Show answer

Answer: A. Yes, you can overload both member and non-member functions in C++

293. Which of the following is an example of function overloading?

  1. Option A: int add(int x, int y) { return x + y; } int add(int x, int y, int z) { return x+y+z;}
  2. Option B: int add(int x, int y) { return x + y; } float add(int x, int y) { return x + y;}
  3. Option C: int add(int x, int y) { return x + y; } int subtract(int x, int y) { return x - y; }
  4. Option D: All of the above
Show answer

Answer: A. int add(int x, int y) { return x + y; } int add(int x, int y, int z) { return x+y+z;}

294. What is an inline function in C++?

  1. Option A: A function that takes an argument of type inline
  2. Option B: A function that is defined with the inline keyword
  3. Option C: A function that is executed sequentially
  4. Option D: A function that is expanded inline by the compiler
Show answer

Answer: B. A function that is defined with the inline keyword

295. What is the advantage of using an inline function?

  1. Option A: It reduces the size of the program
  2. Option B: It reduces the function call overhead
  3. Option C: It increases the performance of the program
  4. Option D: It allows for recursion
Show answer

Answer: B. It reduces the function call overhead

296. Which keyword is used to declare an inline function in C++?

  1. Option A: function
  2. Option B: inline
  3. Option C: def
  4. Option D: define
Show answer

Answer: B. inline

297. Can a function that returns void be inline in C++?

  1. Option A: Yes, any function can be declared inline
  2. Option B: No, only functions that return a value can be inline
  3. Option C: It depends on the implementation
  4. Option D: None of the above
Show answer

Answer: A. Yes, any function can be declared inline

298. Which of the following statements is true about inline functions in C++?

  1. Option A: Inline functions cannot be recursive
  2. Option B: Inline functions cannot contain loops
  3. Option C: Inline functions cannot be overloaded
  4. Option D: Inline functions cannot have default arguments
Show answer

Answer: A. Inline functions cannot be recursive

299. How does the compiler treat inline functions in C++?

  1. Option A: It generates a separate function call for each call to the inline function
  2. Option B: It replaces the function call with the actual function code at the point of the call
  3. Option C: It generates an error if the function is not defined inline
  4. Option D: It generates a jump instruction to the function code at the point of the call
Show answer

Answer: B. It replaces the function call with the actual function code at the point of the call

300. Can a function that is defined in a separate source file be inline in C++?

  1. Option A: Yes, as long as the function is declared inline in the header file
  2. Option B: No, inline functions must be defined in the same source file as the caller
  3. Option C: It depends on the implementation of the compiler
  4. Option D: None of the above
Show answer

Answer: B. No, inline functions must be defined in the same source file as the caller

301. Which of the following is an example of an inline function in C++?

  1. Option A: int add(int a, int b) { return a + b; }
  2. Option B: void print_hello() { std::cout << "Hello, world!" << std::endl; }
  3. Option C: double square(double x) {return x*x;}
  4. Option D: class Rectangle { public: inline int area() { return width * height; } };
Show answer

Answer: D. class Rectangle { public: inline int area() { return width * height; } };

302. Which of the following is a disadvantage of using inline functions in C++?

  1. Option A: It can increase the size of the program
  2. Option B: It can decrease the performance of the program
  3. Option C: It can lead to code bloat
  4. Option D: It can lead to name collisions
Show answer

Answer: A. It can increase the size of the program

303. Which of the following is a good candidate for an inline function in C++?

  1. Option A: A function that performs complex calculations
  2. Option B: A function that is called frequently and has a short body
  3. Option C: A function that takes a long time to execute
  4. Option D: A function that is rarely called and has a long body
Show answer

Answer: B. A function that is called frequently and has a short body

304. What is an inline function in C++? (Repeated concept)

  1. Option A: A function defined with the "inline" keyword, which is a suggestion to the compiler to perform inline expansion of the function
  2. Option B: A function defined with the "inline" keyword, which is a requirement for the compiler to perform inline expansion of the function
  3. Option C: A function that is always expanded inline by the compiler, regardless of how it is defined
  4. Option D: A function that is never expanded inline by the compiler, regardless of how it is defined
Show answer

Answer: A. A function defined with the "inline" keyword, which is a suggestion to the compiler to perform inline expansion of the function

305. What is the advantage of using inline functions in C++? (Repeated concept)

  1. Option A: They are faster than regular functions
  2. Option B: They reduce the executable size of a program
  3. Option C: They can be used to define function templates
  4. Option D: They make it easier to overload functions
Show answer

Answer: A. They are faster than regular functions

306. When should you use an inline function in C++?

  1. Option A: When the function is small and simple
  2. Option B: When the function is called frequently
  3. Option C: When the function has a lot of parameters
  4. Option D: When the function is large and complex
Show answer

Answer: A. When the function is small and simple

307. What is the syntax for defining an inline function in C++?

  1. Option A: inline int function_name(int param1, int param2) {}
  2. Option B: void inline function_name(int param1, int param2) {}
  3. Option C: int inline function_name(int param1, int param2) {}
  4. Option D: inline function_name(int param1, int param2) {}
Show answer

Answer: A. inline int function_name(int param1, int param2) {}

308. Can a member function of a class be inline in C++?

  1. Option A: Yes, as long as it is defined with the "inline" keyword
  2. Option B: No, member functions cannot be inline in C++
  3. Option C: Yes, as long as it is defined with the "inline" keyword and the function body is defined inside the class definition
  4. Option D: It depends on the implementation
Show answer

Answer: C. Yes, as long as it is defined with the "inline" keyword and the function body is defined inside the class definition

309. What is the purpose of the "inline" keyword in C++?

  1. Option A: To indicate that a function is a friend of a class
  2. Option B: To require the compiler to perform inline expansion of a function
  3. Option C: To suggest to the compiler to perform inline expansion of a function
  4. Option D: To indicate that a function is a virtual function
Show answer

Answer: C. To suggest to the compiler to perform inline expansion of a function

310. Which of the following is a disadvantage of using inline functions in C++? (Repeated concept)

  1. Option A: They can increase the size of the executable code
  2. Option B: They can slow down the program execution
  3. Option C: They can make debugging more difficult
  4. Option D: There are no disadvantages to using inline functions
Show answer

Answer: A. They can increase the size of the executable code

311. Can a function defined in a header file be inline in C++?

  1. Option A: Yes, as long as it is defined with the "inline" keyword
  2. Option B: No, functions defined in header files cannot be inline in C++
  3. Option C: Yes, as long as it is defined with the "inline" keyword and the function body is defined inside the header file
  4. Option D: It depends on the compiler
Show answer

Answer: C. Yes, as long as it is defined with the "inline" keyword and the function body is defined inside the header file

312. What is a default argument in C++?

  1. Option A: An argument that is automatically assigned the value 0
  2. Option B: An argument that is assigned the value of the previous argument
  3. Option C: An argument that is assigned a value if no other value is provided
  4. Option D: An argument that is assigned a random value
Show answer

Answer: C. An argument that is assigned a value if no other value is provided

313. Which of the following is true about default arguments?

  1. Option A: They must be specified in the function declaration and definition
  2. Option B: They can only be of basic data types such as int and float
  3. Option C: They must always come at the beginning of the argument list
  4. Option D: They cannot be of array types
Show answer

Answer: A. They must be specified in the function declaration and definition

314. Which of the following is an example of a function that uses a default argument?

  1. Option A: int add(int x, int y)
  2. Option B: float divide(float a, float b, float c = 1.0)
  3. Option C: void print()
  4. Option D: char getChar(char c = 'a')
Show answer

Answer: B. float divide(float a, float b, float c = 1.0)

315. What is the order in which arguments are passed to a function?

  1. Option A: Regular arguments first, followed by default arguments
  2. Option B: Default arguments first, followed by regular arguments
  3. Option C: Random order
  4. Option D: None of the above
Show answer

Answer: A. Regular arguments first, followed by default arguments

316. Which of the following is true about default arguments in relation to function overloading?

  1. Option A: Default arguments are not allowed in function overloading
  2. Option B: Default arguments must be the same for all functions in an overload set
  3. Option C: Default arguments are allowed, but only for one function in an overload set
  4. Option D: Default arguments must be different for all functions in an overload set
Show answer

Answer: C. Default arguments are allowed, but only for one function in an overload set

317. What is the benefit of using default arguments?

  1. Option A: It makes the code more efficient
  2. Option B: It allows for fewer function overloads
  3. Option C: It improves code readability
  4. Option D: It allows for more complex programs
Show answer

Answer: B. It allows for fewer function overloads

318. What happens if a default argument is specified in both the function declaration and definition?

  1. Option A: The code will not compile
  2. Option B: The argument specified in the definition will be used
  3. Option C: The argument specified in the declaration will be used
  4. Option D: The default argument will be ignored
Show answer

Answer: A. The code will not compile

319. What are default arguments in C++? (Repeated concept)

  1. Option A: Arguments that are automatically initialized with a default value.
  2. Option B: Arguments that are passed by value.
  3. Option C: Arguments that are passed by reference.
  4. Option D: Arguments that are passed by pointer.
Show answer

Answer: A. Arguments that are automatically initialized with a default value.

320. Where should default arguments be specified in a function declaration?

  1. Option A: Before the function name.
  2. Option B: After the function name.
  3. Option C: Before the return type.
  4. Option D: After the return type.
Show answer

Answer: B. After the function name.

321. What is the purpose of default arguments? (Repeated concept)

  1. Option A: To make functions more efficient.
  2. Option B: To make it easier to pass arguments to a function.
  3. Option C: To allow a function to be overloaded.
  4. Option D: To provide a default value for a parameter if one is not specified.
Show answer

Answer: D. To provide a default value for a parameter if one is not specified.

322. When are default arguments evaluated?

  1. Option A: At runtime.
  2. Option B: At compile time.
  3. Option C: At link time.
  4. Option D: At load time.
Show answer

Answer: A. At runtime.

323. What happens if a default argument is specified in both the function declaration and the function definition? (Repeated concept)

  1. Option A: The program will not compile.
  2. Option B: The default argument specified in the function definition will be used.
  3. Option C: The default argument specified in the function declaration will be used.
  4. Option D: Both default arguments will be used.
Show answer

Answer: A. The program will not compile.

324. What is the syntax for specifying a default argument?

  1. Option A: argumentType argumentName = defaultValue
  2. Option B: argumentType defaultValue argumentName
  3. Option C: defaultValue argumentType argumentName
  4. Option D: argumentName = defaultValue
Show answer

Answer: A. argumentType argumentName = defaultValue

325. Which of the following is true about classes in C++?

  1. Option A: A class is a blueprint for objects
  2. Option B: A class is an object
  3. Option C: A class is a function
  4. Option D: A class is a data type
Show answer

Answer: A. A class is a blueprint for objects

326. Which of the following keywords is used to create an object of a class?

  1. Option A: new
  2. Option B: this
  3. Option C: object
  4. Option D: none of the above
Show answer

Answer: A. new

327. Which of the following access specifiers is used to make class members accessible only within the same class?

  1. Option A: public
  2. Option B: private
  3. Option C: protected
  4. Option D: none of the above
Show answer

Answer: B. private

328. Which of the following is a constructor?

  1. Option A: A function that is used to create an object of a class
  2. Option B: A function that is used to destroy an object of a class
  3. Option C: A function that is used to allocate memory for an object of a class
  4. Option D: A function that is used to deallocate memory for an object of a class
Show answer

Answer: A. A function that is used to create an object of a class

329. What is encapsulation in C++?

  1. Option A: Combining data members and member functions in a single unit
  2. Option B: Making class members accessible only within the same class
  3. Option C: Creating objects of a class
  4. Option D: None of the above
Show answer

Answer: A. Combining data members and member functions in a single unit

330. What is a class in C++?

  1. Option A: A user-defined data type
  2. Option B: A built-in data type
  3. Option C: A function
  4. Option D: A pointer to a variable
Show answer

Answer: A. A user-defined data type

331. Which of the following is true about a static member of a class?

  1. Option A: It is shared by all objects of the class
  2. Option B: It is specific to each object of the class
  3. Option C: It can be accessed using the object of the class
  4. Option D: It cannot be accessed using the object of the class
Show answer

Answer: A. It is shared by all objects of the class

332. Which of the following is used to create a copy of an object in C++?

  1. Option A: Object cloning
  2. Option B: Object duplication
  3. Option C: Object copying
  4. Option D: Object creation
Show answer

Answer: C. Object copying

333. Which of the following is used to initialize the data members of an object of a class?

  1. Option A: Constructors
  2. Option B: Destructors
  3. Option C: assignment operators
  4. Option D: Copy constructors
Show answer

Answer: A. Constructors

334. Which of the following is true about friend functions in C++?

  1. Option A: Friend functions are class members
  2. Option B: Friend functions can access private and protected members of a class
  3. Option C: Friend functions can be called using an object of the class
  4. Option D: Friend functions cannot be defined outside the class
Show answer

Answer: B. Friend functions can access private and protected members of a class

335. What is an object in C++?

  1. Option A: An instance of a class
  2. Option B: A type of data
  3. Option C: A function
  4. Option D: A pointer to a variable
Show answer

Answer: A. An instance of a class

336. Which of the following access specifiers in C++ allows the member to be accessed by any function or class in the program?

  1. Option A: Private
  2. Option B: Protected
  3. Option C: Public
  4. Option D: Friend
Show answer

Answer: C. Public

337. Which access specifier in C++ allows a member function or variable to be accessed only by the same class and its friends?

  1. Option A: Private
  2. Option B: Public
  3. Option C: Protected
  4. Option D: Friend
Show answer

Answer: A. Private

338. Which access specifier in C++ allows a member function or variable to be accessed by the same class, its derived classes, and its friends?

  1. Option A: Private
  2. Option B: Public
  3. Option C: Protected
  4. Option D: Friend
Show answer

Answer: C. Protected

339. Which of the following is true about access specifiers in C++?

  1. Option A: They determine the visibility of a member outside of the class.
  2. Option B: They determine the data type of a member.
  3. Option C: They determine the scope of a member within the class.
  4. Option D: They determine the storage location of a member.
Show answer

Answer: A. They determine the visibility of a member outside of the class.

340. Which of the following access specifiers is used to hide the implementation details of a class from the user?

  1. Option A: Private
  2. Option B: Public
  3. Option C: Protected
  4. Option D: Friend
Show answer

Answer: A. Private

341. Which access specifier in C++ allows a member function or variable to be accessed by any class or function that is declared as a friend of the class?

  1. Option A: Private
  2. Option B: Public
  3. Option C: Protected
  4. Option D: Friend
Show answer

Answer: D. Friend

342. Which access specifier in C++ allows a member function or variable to be accessed by the same class and its derived classes?

  1. Option A: Private
  2. Option B: Public
  3. Option C: Protected
  4. Option D: Friend
Show answer

Answer: C. Protected

343. Which access specifier in C++ allows a member function or variable to be accessed by any function or class within the same namespace?

  1. Option A: Private
  2. Option B: Public
  3. Option C: Protected
  4. Option D: Friend
Show answer

Answer: B. Public

344. Which of the following access specifiers in C++ is used to prevent a member from being accessed outside of the class definition?

  1. Option A: public
  2. Option B: private
  3. Option C: protected
  4. Option D: friend
Show answer

Answer: B. private

345. Which access specifier allows access to a class member only within the class definition?

  1. Option A: public
  2. Option B: private
  3. Option C: protected
  4. Option D: friend
Show answer

Answer: B. private

346. Which access specifier allows access to a class member from any function outside the class definition?

  1. Option A: public
  2. Option B: private
  3. Option C: protected
  4. Option D: friend
Show answer

Answer: A. public

347. Which access specifier allows access to a class member from a derived class?

  1. Option A: public
  2. Option B: private
  3. Option C: protected
  4. Option D: friend
Show answer

Answer: C. protected

348. Which access specifier allows a member function to access all members of a class?

  1. Option A: public
  2. Option B: private
  3. Option C: protected
  4. Option D: friend
Show answer

Answer: B. private

349. What is the default access specifier for a class in C++?

  1. Option A: public
  2. Option B: private
  3. Option C: protected
  4. Option D: friend
Show answer

Answer: B. private

350. Which access specifier allows a friend function to access all members of a class?

  1. Option A: public
  2. Option B: private
  3. Option C: protected
  4. Option D: friend
Show answer

Answer: D. friend

351. Which access specifier allows access to a class member from any class?

  1. Option A: public
  2. Option B: private
  3. Option C: protected
  4. Option D: friend
Show answer

Answer: A. public

352. Which access specifier should be used for class members that need to be accessed by functions outside the class definition?

  1. Option A: public
  2. Option B: private
  3. Option C: protected
  4. Option D: friend
Show answer

Answer: A. public

353. Which access specifier should be used for class members that should only be accessed within the class definition?

  1. Option A: public
  2. Option B: private
  3. Option C: protected
  4. Option D: friend
Show answer

Answer: B. private

354. What is the dot operator used for in C++?

  1. Option A: To declare objects
  2. Option B: To access a member of an object
  3. Option C: To access a function of a class
  4. Option D: To access a class variable
Show answer

Answer: B. To access a member of an object

355. Which of the following is an example of an object?

  1. Option A: int x;
  2. Option B: string s;
  3. Option C: MyClass obj;
  4. Option D: double y;
Show answer

Answer: C. MyClass obj;

356. Which of the following operators is used to access a member of an object?

  1. Option A: .
  2. Option B: ->
  3. Option C: ::
  4. Option D: :
Show answer

Answer: A. .

357. Which of the following is used to initialize an object?

  1. Option A: The constructor
  2. Option B: The destructor
  3. Option C: The copy constructor
  4. Option D: The assignment operator
Show answer

Answer: A. The constructor

358. Which of the following access specifiers allows a member to be accessed from any function?

  1. Option A: Public
  2. Option B: Private
  3. Option C: Protected
  4. Option D: Friend
Show answer

Answer: A. Public

359. What is the keyword used to declare a class in C++?

  1. Option A: class
  2. Option B: object
  3. Option C: struct
  4. Option D: member
Show answer

Answer: A. class

360. Which of the following is used to destroy an object?

  1. Option A: The constructor
  2. Option B: The destructor
  3. Option C: The copy constructor
  4. Option D: The assignment operator
Show answer

Answer: B. The destructor

361. Which of the following is true about an object in C++?

  1. Option A: It is an instance of a class
  2. Option B: It cannot be passed as a parameter to a function
  3. Option C: It does not have any data members or member functions
  4. Option D: It can be created without a class definition
Show answer

Answer: A. It is an instance of a class

362. What is the difference between the dot operator (.) and the arrow operator (->) in C++?

  1. Option A: The dot operator is used with pointers, while the arrow operator is used with objects.
  2. Option B: The dot operator is used to access static members, while the arrow operator is used to access non-static members.
  3. Option C: The dot operator is used to access non-static members, while the arrow operator is used with pointers to access non-static members.
  4. Option D: The dot operator is used to access public members, while the arrow operator is used to access private members.
Show answer

Answer: C. The dot operator is used to access non-static members, while the arrow operator is used with pointers to access non-static members.

363. Which operator is used to access the members of an object in C++?

  1. Option A: .
  2. Option B: &
  3. Option C: ->
  4. Option D: ::
Show answer

Answer: A. .

364. Which keyword is used to define a member function outside the class definition in C++?

  1. Option A: here
  2. Option B: that
  3. Option C: this
  4. Option D: none of the above
Show answer

Answer: D. none of the above

365. Which of the following is true about object-oriented programming in C++?

  1. Option A: It is a procedural programming language
  2. Option B: Objects encapsulate data and behavior
  3. Option C: It supports only single inheritance
  4. Option D: All of the above
Show answer

Answer: B. Objects encapsulate data and behavior

366. Which of the following is true about a member function in C++?

  1. Option A: It can be defined inside or outside the class definition
  2. Option B: It can only be defined inside the class definition
  3. Option C: It can only be defined outside the class definition
  4. Option D: None of the above
Show answer

Answer: A. It can be defined inside or outside the class definition

367. Which keyword is used to access the data members of an object inside a member function in C++?

  1. Option A: private
  2. Option B: public
  3. Option C: protected
  4. Option D: this
Show answer

Answer: D. this

368. Which of the following is true about object creation in C++?

  1. Option A: It is done using the new operator
  2. Option B: It is done using the malloc() function
  3. Option C: It is done using the class constructor
  4. Option D: None of the above
Show answer

Answer: C. It is done using the class constructor

369. Which of the following is true about constructors in C++?

  1. Option A: They are used to allocate memory for objects
  2. Option B: They are used to initialize the data members of an object
  3. Option C: They are used to deallocate memory for objects
  4. Option D: None of the above
Show answer

Answer: B. They are used to initialize the data members of an object

370. Which of the following is true about destructors in C++?

  1. Option A: They are used to allocate memory for objects
  2. Option B: They are used to initialize the data members of an object
  3. Option C: They are used to deallocate memory for objects
  4. Option D: None of the above
Show answer

Answer: C. They are used to deallocate memory for objects

371. Which of the following is true about static member functions in C++?

  1. Option A: They can access only static data members of a class
  2. Option B: They can access only non-static data members of a class
  3. Option C: They can access both static and non-static data members of a class
  4. Option D: None of the above
Show answer

Answer: A. They can access only static data members of a class

372. Which of the following is true about friend functions in C++?

  1. Option A: They are member functions of a class
  2. Option B: They can access private and protected members of a class
  3. Option C: They can access only public members of a class
  4. Option D: None of the above
Show answer

Answer: B. They can access private and protected members of a class

373. What is a member function in C++?

  1. Option A: A function that can only be used outside of a class
  2. Option B: A function that belongs to a class
  3. Option C: A function that can only be used inside of a class
  4. Option D: A function that belongs to the global namespace
Show answer

Answer: B. A function that belongs to a class

374. How are member functions defined in C++?

  1. Option A: Inside the class definition
  2. Option B: Outside the class definition
  3. Option C: Both A and B
  4. Option D: Neither A nor B
Show answer

Answer: C. Both A and B

375. Which keyword is used to define a member function outside of a class in C++?

  1. Option A: public
  2. Option B: private
  3. Option C: protected
  4. Option D: none of the above
Show answer

Answer: D. none of the above

376. Which of the following is a valid syntax for defining a member function outside of a class in C++?

  1. Option A: void MyClass::myFunction() {}
  2. Option B: MyClass: void myFunction() {}
  3. Option C: void myFunction() ::MyClass {}
  4. Option D: None of the above
Show answer

Answer: A. void MyClass::myFunction() {}

377. Which of the following is true about member functions in C++?

  1. Option A: They have access to the private data members of a class
  2. Option B: They can only access public data members of a class
  3. Option C: They cannot access any data members of a class
  4. Option D: None of the above
Show answer

Answer: A. They have access to the private data members of a class

378. What is the implicit parameter in a member function in C++?

  1. Option A: A pointer to the object that called the function
  2. Option B: A pointer to the object that contains the function
  3. Option C: A pointer to the object that was passed as an argument to the function
  4. Option D: None of the above
Show answer

Answer: A. A pointer to the object that called the function

379. Which keyword is used to access the implicit parameter in a member function in C++?

  1. Option A: this
  2. Option B: that
  3. Option C: here
  4. Option D: none of the above
Show answer

Answer: A. this

380. Which of the following is true about the this pointer in C++?

  1. Option A: It is a constant pointer
  2. Option B: It points to the object that called the member function
  3. Option C: It is an integer value that represents the memory address of the object
  4. Option D: None of the above
Show answer

Answer: B. It points to the object that called the member function

381. Which of the following is true about inline member functions in C++?

  1. Option A: They are defined outside the class definition
  2. Option B: They are always faster than non-inline member functions
  3. Option C: They are used for small functions that are called frequently
  4. Option D: None of the above
Show answer

Answer: C. They are used for small functions that are called frequently

382. Which of the following is true about const member functions in C++?

  1. Option A: They cannot modify the data members of a class
  2. Option B: They are declared using the const keyword after the parameter list
  3. Option C: They can only be used inside the class definition
  4. Option D: None of the above
Show answer

Answer: A. They cannot modify the data members of a class

383. What is a member function in C++? (Repeated Question)

  1. Option A: A function that is defined inside a class definition
  2. Option B: A function that is defined outside a class definition
  3. Option C: A function that is not related to any class
  4. Option D: None of the above
Show answer

Answer: A. A function that is defined inside a class definition

384. How is a member function defined inside a class definition in C++?

  1. Option A: using the :: operator
  2. Option B: using the -> operator
  3. Option C: using the . operator
  4. Option D: using the function name and parameter list
Show answer

Answer: D. using the function name and parameter list

385. What is the purpose of the "this" pointer in C++?

  1. Option A: It points to the object on which the member function is called
  2. Option B: It points to the class definition
  3. Option C: It points to the current function
  4. Option D: None of the above
Show answer

Answer: A. It points to the object on which the member function is called

386. How is a member function defined outside a class definition in C++?

  1. Option A: using the function name and parameter list
  2. Option B: using the scope resolution operator and the class name
  3. Option C: using the class name and parameter list
  4. Option D: None of the above
Show answer

Answer: B. using the scope resolution operator and the class name

387. What is the syntax for calling a member function of an object in C++?

  1. Option A: object.member_function()
  2. Option B: object->member_function()
  3. Option C: both A and B
  4. Option D: None of the above
Show answer

Answer: C. both A and B

388. What is the default access specifier for a member function in C++?

  1. Option A: public
  2. Option B: private
  3. Option C: protected
  4. Option D: None of the above
Show answer

Answer: B. private

389. Can a member function be overloaded in C++?

  1. Option A: Yes
  2. Option B: No
  3. Option C: It depends on the access specifier
  4. Option D: None of the above
Show answer

Answer: A. Yes

390. Can a member function be declared inside a class definition and defined outside the class definition in C++?

  1. Option A: Yes
  2. Option B: No
  3. Option C: It depends on the access specifier
  4. Option D: None of the above
Show answer

Answer: A. Yes

391. Can a member function access the private data members of a class in C++?

  1. Option A: Yes
  2. Option B: No
  3. Option C: depends on the access specifier
  4. Option D: None of the above
Show answer

Answer: A. Yes

392. What is the purpose of the const keyword in a member function declaration in C++?

  1. Option A: It indicates that the function is a constructor
  2. Option B: It indicates that the function is a destructor
  3. Option C: It indicates that the function does not modify the object on which it is called
  4. Option D: None of the above
Show answer

Answer: C. It indicates that the function does not modify the object on which it is called

393. What is a constructor in C++?

  1. Option A: A function that is used to allocate memory for an object
  2. Option B: A function that is used to initialize the data members of an object
  3. Option C: A function that is used to deallocate memory for an object
  4. Option D: None of the above
Show answer

Answer: B. A function that is used to initialize the data members of an object

394. What is the name of the constructor function in C++?

  1. Option A: init()
  2. Option B: constructor()
  3. Option C: the same as the class name
  4. Option D: None of the above
Show answer

Answer: C. the same as the class name

395. How many constructors can a class have in C++?

  1. Option A: Only one
  2. Option B: More than one
  3. Option C: It depends on the size of the class
  4. Option D: None of the above
Show answer

Answer: B. More than one

396. Which type of constructor is called automatically when an object is created in C++?

  1. Option A: Copy constructor
  2. Option B: Parameterized constructor
  3. Option C: Default constructor
  4. Option D: None of the above
Show answer

Answer: C. Default constructor

397. What is the purpose of the copy constructor in C++?

  1. Option A: It is used to create a copy of an existing object
  2. Option B: It is used to allocate memory for an object
  3. Option C: It is used to delete an existing object
  4. Option D: None of the above
Show answer

Answer: A. It is used to create a copy of an existing object

398. Can a constructor be declared as private in C++?

  1. Option A: Yes
  2. Option B: No
  3. Option C: It depends on the type of constructor
  4. Option D: None of the above
Show answer

Answer: A. Yes

399. Which of the following is true about the default constructor in C++?

  1. Option A: It takes no arguments
  2. Option B: It has an empty body
  3. Option C: It is provided by the compiler if no other constructor is defined
  4. Option D: All of the above
Show answer

Answer: D. All of the above

400. Which of the following is true about the parameterized constructor in C++?

  1. Option A: It takes no arguments
  2. Option B: It has an empty body
  3. Option C: It takes one or more arguments
  4. Option D: None of the above
Show answer

Answer: C. It takes one or more arguments

401. What is the syntax for calling a constructor in C++?

  1. Option A: class_name.constructor_name()
  2. Option B: class_name::constructor_name()
  3. Option C: class_name object_name(argument_list)
  4. Option D: None of the above
Show answer

Answer: C. class_name object_name(argument_list)

402. Which of the following is true about the destructor in C++?

  1. Option A: It is used to allocate memory for an object
  2. Option B: It is used to deallocate memory for an object
  3. Option C: It is used to initialize the data members of an object
  4. Option D: None of the above
Show answer

Answer: B. It is used to deallocate memory for an object

403. What is the this pointer in C++?

  1. Option A: A pointer to the current object
  2. Option B: A pointer to the current function
  3. Option C: A pointer to the current class
  4. Option D: None of the above
Show answer

Answer: A. A pointer to the current object

404. What is the purpose of the this pointer in C++?

  1. Option A: To refer to the object's own data members
  2. Option B: To refer to a different object's data members
  3. Option C: To refer to a different function
  4. Option D: None of the above
Show answer

Answer: A. To refer to the object's own data members

405. What is the syntax for using the this pointer in C++?

  1. Option A: this->data_member;
  2. Option B: (*this).data_member
  3. Option C: Both A and B
  4. Option D: None of the above
Show answer

Answer: C. Both A and B

406. Can the this pointer be modified in C++?

  1. Option A: Yes, it can be modified like any other pointer
  2. Option B: No, it is a constant pointer
  3. Option C: It can be modified only within the same class
  4. Option D: None of above
Show answer

Answer: B. No, it is a constant pointer

407. What is the data type of the this pointer in C++?

  1. Option A: Class type pointer
  2. Option B: Integer pointer
  3. Option C: Void pointer
  4. Option D: None of the above
Show answer

Answer: A. Class type pointer

408. What happens if a member function does not use the this pointer in C++?

  1. Option A: It can cause a compile-time error
  2. Option B: It may still work, but it will not be able to access the object's data members
  3. Option C: The program will crash at runtime
  4. Option D: None of the above
Show answer

Answer: D. None of the above

409. How is the this pointer passed to a member function in C++?

  1. Option A: It is implicitly passed to the function
  2. Option B: It is passed as an argument to the function
  3. Option C: It is not passed to the function
  4. Option D: None of above
Show answer

Answer: A. It is implicitly passed to the function

410. What is the size of the this pointer in C++?

  1. Option A: It is always 4 bytes
  2. Option B: It is always 8 bytes
  3. Option C: It depends on the size of the object
  4. Option D: None of the above
Show answer

Answer: C. It depends on the size of the object

411. Can the this pointer be used in static member functions in C++?

  1. Option A: No, the this pointer is not applicable to static member functions
  2. Option B: Yes, but only if the static function takes an object as a parameter
  3. Option C: It can be used only within the same class
  4. Option D: None of above
Show answer

Answer: A. No, the this pointer is not applicable to static member functions

412. In which operator overload function can the this pointer be used in C++?

  1. Option A: Overloading the assignment operator
  2. Option B: Overloading the equality operator
  3. Option C: Both A and B
  4. Option D: None of the above
Show answer

Answer: C. Both A and B

413. What is this pointer in C++?

  1. Option A: It is a pointer to the current object
  2. Option B: It is a pointer to the current function
  3. Option C: It is a pointer to the base class
  4. Option D: None of the above
Show answer

Answer: A. It is a pointer to the current object

414. In which part of a C++ class is this pointer implicitly passed?

  1. Option A: Constructor
  2. Option B: Destructor
  3. Option C: Member functions
  4. Option D: All of the above
Show answer

Answer: D. All of the above

415. What is the type of this pointer in C++?

  1. Option A: void
  2. Option B: int
  3. Option C: ClassName
  4. Option D: None of the above
Show answer

Answer: C. ClassName

416. Which of the following is a valid use of this pointer in C++?

  1. Option A: To access member variables of the current object
  2. Option B: To access member functions of the current object
  3. Option C: To access static variables of the current object
  4. Option D: All of the above
Show answer

Answer: D. All of the above

417. What is the purpose of this pointer in C++?

  1. Option A: To resolve naming conflicts between member variables and parameters of a function
  2. Option B: To access private member variables of a class
  3. Option C: To access static member variables of a class
  4. Option D: None of the above
Show answer

Answer: A. To resolve naming conflicts between member variables and parameters of a function

418. Which of the following statements is true about this pointer in C++?

  1. Option A: It can be modified by the programmer
  2. Option B: It cannot be modified by the programmer
  3. Option C: It can be null
  4. Option D: None of the above
Show answer

Answer: B. It cannot be modified by the programmer

419. What happens if this pointer is dereferenced when it is null?

  1. Option A: A compile-time error occurs
  2. Option B: A runtime error occurs
  3. Option C: Undefined behavior occurs
  4. Option D: None of the above
Show answer

Answer: C. Undefined behavior occurs

420. What is the use of this pointer in operator overloading in C++?

  1. Option A: To overload the -> operator
  2. Option B: To overload the . operator
  3. Option C: Both A and B
  4. Option D: None of the above
Show answer

Answer: A. To overload the -> operator

421. What is the output of the following code?

  1. Option A: The address of obj1 and obj2 are the same
  2. Option B: The address of obj1 and obj2 are different
  3. Option C: The program will not compile
  4. Option D: The program will crash at runtime
Show answer

Answer: B. The address of obj1 and obj2 are different

422. What is a static data member in C++?

  1. Option A: A data member that is unique to each instance of a class
  2. Option B: A data member that is shared among all instances of a class
  3. Option C: A data member that can be accessed only by static functions
  4. Option D: A data member that cannot be accessed from outside the class
Show answer

Answer: B. A data member that is shared among all instances of a class

423. How is a static data member declared in C++?

  1. Option A: Using the keyword static before the data type
  2. Option B: Using the keyword static before the class name
  3. Option C: Using the keyword static after the data type
  4. Option D: None of the above
Show answer

Answer: A. Using the keyword static before the data type

424. Which of the following statements is true about static data members in C++?

  1. Option A: They are not initialized by default
  2. Option B: They are initialized to 0 by default
  3. Option C: They are initialized to 1 by default
  4. Option D: None of the above
Show answer

Answer: B. They are initialized to 0 by default

425. How is a static function declared in C++?

  1. Option A: Using the keyword static before the return type
  2. Option B: Using the keyword static before the function name
  3. Option C: Using the keyword static after the return type
  4. Option D: None of the above
Show answer

Answer: A. Using the keyword static before the return type

426. Which of the following statements is true about static functions in C++?

  1. Option A: They can access only static data members of the class
  2. Option B: They can access only non-static data members of the class
  3. Option C: They cannot access any data members of the class
  4. Option D: None of the above
Show answer

Answer: A. They can access only static data members of the class

427. Can a static function in C++ access non-static data members of the class?

  1. Option A: Yes, using the this pointer
  2. Option B: Yes, using the static_cast operator
  3. Option C: No, static functions cannot access non-static data members
  4. Option D: None of the above
Show answer

Answer: C. No, static functions cannot access non-static data members

428. Which of the following statements is true about static data members in C++?

  1. Option A: They can be initialized inside the class definition
  2. Option B: They must be initialized inside the class definition
  3. Option C: They can be initialized only outside the class definition
  4. Option D: None of the above
Show answer

Answer: C. They can be initialized only outside the class definition

429. Which of the following statements is true about static functions in C++?

  1. Option A: They cannot access non-static data members
  2. Option B: They can access non-static data members
  3. Option C: They can be virtual
  4. Option D: They can be called using an instance of the class
Show answer

Answer: A. They cannot access non-static data members

430. Which of the following statements is true about static data members in C++?

  1. Option A: They can be accessed using the object of the class
  2. Option B: They can be accessed using the class name and the scope resolution operator
  3. Option C: They can be accessed using the pointer to the object of the class
  4. Option D: All of the above are true
Show answer

Answer: D. All of the above are true

431. What is the output of the following code? (Code involves MyClass::count++, incrementCount called twice)

  1. Option A: Count: 2
  2. Option B: Count: 0
  3. Option C: Count: 1
  4. Option D: None of the above
Show answer

Answer: A. Count: 2

432. What is a static data member in C++?

  1. Option A: A data member that can be accessed only by static functions
  2. Option B: A data member that belongs to the class and not to any instance of the class
  3. Option C: A data member that is created dynamically at runtime
  4. Option D: None of the above
Show answer

Answer: B. A data member that belongs to the class and not to any instance of the class

433. How is a static data member declared In C++?

  1. Option A: With the keyword 'static' and the name of the member
  2. Option B: With the keyword 'static' and the data type of the member
  3. Option C: With the keyword 'static' and the access specifier of the member
  4. Option D: None of the above
Show answer

Answer: B. With the keyword 'static' and the data type of the member

434. Which of the following statements is true about static data members in C++?

  1. Option A: They are initialized to zero by default
  2. Option B: They cannot be initialized inside the class declaration
  3. Option C: They are initialized to their default values by default
  4. Option D: None of the above
Show answer

Answer: A. They are initialized to zero by default

435. What is a static function in C++?

  1. Option A: A function that can be accessed only by static data members
  2. Option B: A function that belongs to the class and not to any instance of the class
  3. Option C: A function that is created dynamically at runtime
  4. Option D: None of the above
Show answer

Answer: B. A function that belongs to the class and not to any instance of the class

436. How is a static function declared in C++?

  1. Option A: With the keyword 'static' and the return type of the function
  2. Option B: With the keyword 'static' and the access specifier of the function
  3. Option C: With the keyword 'static' and the name of the function
  4. Option D: None of the above
Show answer

Answer: A. With the keyword 'static' and the return type of the function

437. Which of the following statements is true about static functions in C++?

  1. Option A: They can be virtual
  2. Option B: They cannot be virtual
  3. Option C: They can be pure virtual
  4. Option D: None of the above
Show answer

Answer: B. They cannot be virtual

438. What is the purpose of static data members and static functions in C++?

  1. Option A: To save memory by sharing data across all instances of the class
  2. Option B: To make the code more modular and easier to maintain
  3. Option C: To create multiple instances of the class with different data
  4. Option D: None of the above
Show answer

Answer: A. To save memory by sharing data across all instances of the class

439. Which of the following statements is true about the scope of a static data member in C++?

  1. Option A: It has class scope and can be accessed using the class name and the scope resolution operator (::)
  2. Option B: It has instance scope and can be accessed using the instance name and the dot operator (.)
  3. Option C: It has global scope and can be accessed from any part of the program
  4. Option D: None of the above
Show answer

Answer: A. It has class scope and can be accessed using the class name and the scope resolution operator (::)

440. Which of the following statements is true about the initialization of a static data member in C++?

  1. Option A: It can be initialized Inside the class declaration using an assignment statement
  2. Option B: It must be initialized outside the class declaration using an assignment statement
  3. Option C: It cannot be initialized
  4. Option D: None of the above
Show answer

Answer: B. It must be initialized outside the class declaration using an assignment statement

441. What is a constant member function in C++?

  1. Option A: A member function that cannot modify any data members of the class
  2. Option B: A member function that can modify any data members of the class
  3. Option C: A member function that cannot be called by const objects of the class
  4. Option D: None of the above
Show answer

Answer: A. A member function that cannot modify any data members of the class

442. How is a constant member function declared in C++?

  1. Option A: Using the keyword const after the function declaration
  2. Option B: Using the keyword const before the function declaration
  3. Option C: Using the keyword const before the return type
  4. Option D: None of the above
Show answer

Answer: A. Using the keyword const after the function declaration

443. Which of the following statements is true about constant member functions in C++?

  1. Option A: They can be called only by constant objects of the class
  2. Option B: They can be called only by non-constant objects of the class
  3. Option C: They can be called by both constant and non-constant objects of the class
  4. Option D: None of the above
Show answer

Answer: C. They can be called by both constant and non-constant objects of the class

444. Can a constant member function modify a static data member of the class?

  1. Option A: Yes, as long as the static data member is declared as mutable
  2. Option B: Yes, as long as the static data member is declared as const
  3. Option C: No, constant member functions cannot modify any data members of the class
  4. Option D: Yes, because static members are not part of the object's state
Show answer

Answer: D. Yes, because static members are not part of the object's state

445. Which of the following statements is true about constant objects in C++?

  1. Option A: They cannot modify any data members of the class
  2. Option B: They can modify only constant data members of the class
  3. Option C: They can modify any data members of the class
  4. Option D: None of the above
Show answer

Answer: A. They cannot modify any data members of the class

446. How is a constant object declared in C++?

  1. Option A: Using the keyword const before the object name
  2. Option B: Using the keyword const after the object name
  3. Option C: Using the keyword const before the class name
  4. Option D: None of the above
Show answer

Answer: A. Using the keyword const before the object name

447. Which of the following statements is true about constant member functions in C++? (Overloading)

  1. Option A: They can be overloaded with non-constant member functions of the same name
  2. Option B: They cannot be overloaded with non-constant member functions of the same name
  3. Option C: They can be overloaded only with other constant member functions of the same name
  4. Option D: None of the above
Show answer

Answer: A. They can be overloaded with non-constant member functions of the same name

448. What is the output of the following code? (const MyClass obj = {5}; obj.value = 10;)

  1. Option A: 5 followed by a compilation error
  2. Option B: 5 followed by 10
  3. Option C: Compilation error followed by 5
  4. Option D: None of the above
Show answer

Answer: A. 5 followed by a compilation error

449. What is a constant member function in C++?

  1. Option A: A member function that cannot be modified
  2. Option B: A member function that can be called on a constant object only
  3. Option C: A member function that does not have any return type
  4. Option D: None of the above
Show answer

Answer: A. A member function that cannot be modified

450. How is a constant member function declared in C++?

  1. Option A: Using the keyword const after the function name
  2. Option B: Using the keyword const after the return type
  3. Option C: Using the keyword const before the function name
  4. Option D: None of the above
Show answer

Answer: A. Using the keyword const after the function name

451. Which of the following statements is true about constant objects in C++?

  1. Option A: They cannot modify the data members of the class
  2. Option B: They can modify the data members of the class
  3. Option C: They can modify the data members of the class only if they are declared mutable
  4. Option D: None of the above
Show answer

Answer: A. They cannot modify the data members of the class

452. Can a non-constant member function be called on a constant object in C++?

  1. Option A: Yes, but only if the function does not modify any data members of the class
  2. Option B: No, a non-constant member function cannot be called on a constant object
  3. Option C: Yes, but only if the function is declared const
  4. Option D: None of the above
Show answer

Answer: B. No, a non-constant member function cannot be called on a constant object

453. Which of the following statements is true about constant objects in C++?

  1. Option A: They can be created using the const keyword before the class name
  2. Option B: They can be created using the const keyword after the object name
  3. Option C: They can be created using the const keyword before the object name
  4. Option D: None of the above
Show answer

Answer: C. They can be created using the const keyword before the object name

454. Which of the following statements is true about constant objects in C++?

  1. Option A: They can call non-constant member functions of the class
  2. Option B: They cannot call non-constant member functions of the class
  3. Option C: They can call non-constant member functions of the class only if the functions are declared const
  4. Option D: None of the above
Show answer

Answer: B. They cannot call non-constant member functions of the class

455. Which of the following statements is true about constant objects in C++?

  1. Option A: They can access only constant member functions of the class
  2. Option B: They can access only non-constant member functions of the class
  3. Option C: They can access both constant and non-constant member functions of the class
  4. Option D: None of the above
Show answer

Answer: A. They can access only constant member functions of the class

456. Which of the following statements is true about constant member functions in C++? (Duplicate logic)

  1. Option A: They cannot modify the data members of the class
  2. Option B: They can modify the data members of the class only if they are declared mutable
  3. Option C: They can modify the data members of the class
  4. Option D: None of the above
Show answer

Answer: A. They cannot modify the data members of the class

457. What is the output of the following code? (const MyClass obj = {10}; obj.printValue();)

  1. Option A: Value: 10
  2. Option B: Value: 0
  3. Option C: The code will not compile because the object is declared const
  4. Option D: None of the above
Show answer

Answer: A. Value: 10

3.4 Features of object-oriented programming

21 questions · ACtE0304

458. If derived class has constructor, which is called first?

Aasadh 2081 exam
  1. Option A: Derived constructor first
  2. Option B: Base constructor first
  3. Option C: Only derived called
  4. Option D: Only base called
Show hint

Initialize base before derived.

Show answer

Answer: B. Base constructor first

Base class constructor is called first to initialize base class members before derived class constructor.

459. Which operators can be overloaded in C++?

  1. Option A: Arithmetic (+, -, *, /, %)
  2. Option B: Comparison (==, !=, <, >, <=, >=)
  3. Option C: Logical (&&, ||, !)
  4. Option D: All of the above
Show hint

Most operators can be overloaded in C++.

Show answer

Answer: D. All of the above

All arithmetic, comparison, and logical operators can be overloaded in C++, except for ::, ., .*, and ?:

460. What is Inheritance in OOP?

  1. Option A: Wrapping data into single class
  2. Option B: Deriving new classes from existing
  3. Option C: Overloading of classes
  4. Option D: Classes with same names
Show hint

Creating new classes based on existing ones.

Show answer

Answer: B. Deriving new classes from existing

Inheritance allows creating new classes from existing classes, inheriting properties and methods.

461. What is single-level inheritance?

  1. Option A: Class from multiple bases
  2. Option B: Class from single base
  3. Option C: Base from multiple derived
  4. Option D: Non-inheritable class
Show hint

One parent, one child.

Show answer

Answer: B. Class from single base

Single-level inheritance occurs when a derived class inherits from exactly one base class.

462. What must be overloaded as member function in C++?

  1. Option A: = operator
  2. Option B: [] operator
  3. Option C: () operator
  4. Option D: All of the above
Show hint

Certain operators have special requirements.

Show answer

Answer: D. All of the above

=, [], and () operators must be overloaded as member functions, not global functions.

463. What is operator overloading in C++?

  1. Option A: Using operators multiple times
  2. Option B: Defining custom behavior for operators with objects
  3. Option C: Creating new operators
  4. Option D: Applying operators to different types
Show hint

Complex c1 + c2 - how does compiler know what + means for Complex?

Show answer

Answer: B. Defining custom behavior for operators with objects

Operator overloading: defining custom behavior for C++ operators when applied to user-defined types. Syntax: ReturnType operator@(parameters) { }. Examples: Complex operator+(const Complex& a, const Complex& b) { return Complex(a.real+b.real, a.imag+b.imag); }. Member function: Complex operator+(const Complex& other) const { return Complex(real+other.real, imag+other.imag); }. Non-member: friend Complex operator+(const Complex& a, const Complex& b). Overloadable: arithmetic (+,-,*,/,%), comparison (==,!=,<,>,<=,>=), logical (&&,||,!), bitwise (&,|,^,~,<<,>>), assignment (=,+=,-=,*=,/=,%=), subscript ([]), function call (()), member access (->), increment/decrement (++,--), smart pointer (* and ->). Cannot overload: scope resolution (::), member selection (.), pointer-to-member (.*), ternary (?:), sizeof, typeid. Member-only operators: assignment (=), subscript ([]), function call (()), member access (->). Unary vs binary: prefix/postfix increment differentiated by dummy int parameter. Example: MyClass& operator++() { /* prefix */ } vs MyClass operator++(int) { /* postfix */ }. Return types: arithmetic return by value, assignment return by reference (&). Const correctness: operator+(const MyClass&) const. Chaining: assignment returns reference enabling a=b=c. Implicit conversion: operator int() { return value; } converts object to int. Conversion constructor: MyClass(int) { } converts int to MyClass. Advantages: intuitive syntax (obj1 + obj2 vs obj1.add(obj2)), natural expression. Disadvantages: can confuse (+ might not mean traditional addition), complicates implementation. Best practice: maintain expected semantics, avoid surprising behavior. Example: string concatenation with +, vector index with []. Understanding operator overloading essential for creating natural-feeling APIs.

464. What is data conversion (type conversion) in C++?

  1. Option A: Converting strings to numbers
  2. Option B: Implicit or explicit conversion between types
  3. Option C: Converting variables during assignment
  4. Option D: Changing data structure types
Show hint

int i = 5.5; - automatic conversion from double to int, or cast for control.

Show answer

Answer: B. Implicit or explicit conversion between types

Data conversion: changing one type to another. Implicit (automatic): int x = 5.5; converts double to int (loses precision). Explicit (casting): (int)5.5, int(5.5) (C-style), static_cast<int>(5.5) (C++ style). C++ casts: (1) static_cast<T>(value) type-safe conversion (int from double, base to derived). (2) dynamic_cast<T*>(ptr) safe polymorphic conversion (returns null if invalid). (3) reinterpret_cast<T*>(ptr) unsafe, bitwise reinterpretation (pointer to int). (4) const_cast<T&>(value) adds/removes const. Implicit conversion rules: arithmetic promotion (int to double), pointer conversion (derived* to base*), user-defined conversion (conversion constructor, conversion operator). Conversion constructor: class MyClass { MyClass(int x) { } }; int i=5; MyClass m = i; implicit conversion via constructor. Conversion operator: operator int() { return value; }; int i = obj; implicit conversion via operator. Narrowing: converting larger type to smaller (double to int) loses data - modern C++ warns/errors in some contexts. Example: std::vector<int> v = {1, 2, 3.5}; error (3.5 narrowing to 3). Const conversion: const_cast<string&>(const_str) removes const. Pointer conversion: static_cast<Base*>(derived_ptr) safe, dynamic_cast<Derived*>(base_ptr) safe with RTTI. String conversions: stoi(), stof(), to_string() in modern C++. Best practice: explicit casts for clarity, avoid unsafe reinterpret_cast, use static_cast for type-safe conversions. Understanding conversions crucial for type safety and preventing errors.

465. What is inheritance in C++ - specifically single inheritance?

  1. Option A: Deriving multiple classes from multiple bases
  2. Option B: Single derived class from single base class
  3. Option C: Classes inheriting from interface
  4. Option D: Sharing methods between classes
Show hint

class Derived : public Base { } - one parent, one child.

Show answer

Answer: B. Single derived class from single base class

Single inheritance: derived class inherits from one base class. Syntax: class Derived : public Base { }. Access: public (inherits as public), private (inherits as private), protected (inherits as protected). Characteristics: (1) Derived is-a Base relationship. (2) Inherits all non-private members. (3) Can override virtual functions. (4) Constructor chains. Example: class Vehicle { protected: string make; public: virtual void drive() { } }; class Car : public Vehicle { public: void drive() override { cout << "Driving car"; } }. Public inheritance: public members stay public, protected stay protected. Private inheritance: public/protected become private (rarely used). Protected inheritance: public become protected, protected stay protected. Method override: derived defines function with same signature as base. Virtual call: Vehicle *v = new Car(); v->drive() calls Car::drive(). Member access: Car can access public/protected Vehicle members. Hidden: if derived defines non-virtual function with same name as base, hides base version. Constructor: derived constructor must call base constructor (explicitly or implicitly). Initialization: Car() : Vehicle(args) { } initializes base first. Disadvantage single inheritance: less flexible than multiple inheritance. Code reuse: inherit common functionality from base. Polymorphism: base pointer/reference points to derived object. Diamond problem: avoided (only one base). Best practice: public inheritance for is-a relationships, prefer composition when not true is-a. Understanding single inheritance crucial for OOP and code reuse.

466. What is multiple inheritance in C++?

  1. Option A: One class inheriting from multiple base classes
  2. Option B: Multiple classes inheriting from single base
  3. Option C: Inheritance chain (A->B->C)
  4. Option D: Inheriting from inherited classes
Show hint

class Derived : public Base1, public Base2 { } - two parents.

Show answer

Answer: A. One class inheriting from multiple base classes

Multiple inheritance: derived class inherits from multiple base classes. Syntax: class Derived : public Base1, public Base2 { }. Mix access: class Derived : public A, private B, protected C { }. Uses: combining unrelated features from multiple bases. Example: class Employee { virtual void work() { } }; class Manager { virtual void manage() { } }; class ProjectManager : public Employee, public Manager { void work() override { } void manage() override { } }. Diamond problem: if both bases inherit from common ancestor. Example: class A { }; class B : public A { }; class C : public A { }; class D : public B, public C { }; D has two copies of A (ambiguous). Solution 1 - Virtual inheritance: class B : virtual public A, class C : virtual public A creates single A. Virtual base: D has one A instance, accessed via B and C. Initialization: D() : B(args), C(args), A(args) { } must initialize virtual base explicitly. Ambiguity resolution: B::func() or C::func() if both define same. Complexity: multiple inheritance increases complexity, harder to understand. Best practice: avoid unless necessary, prefer composition (has-a over is-a). Interface classes: pure virtual (resembles multiple inheritance). Mixins: small classes with specific functionality (thread-safe, comparable). Modern C++: prefer composition and single inheritance. Testing: harder with multiple inheritance (more dependencies). Use case: practical multiple inheritance uncommon in modern code. Understanding multiple inheritance important for legacy code and advanced patterns.

467. What is multilevel inheritance in C++?

  1. Option A: Single inheritance repeated in chain
  2. Option B: Multiple inheritance levels (A->B->C)
  3. Option C: Inheriting same level
  4. Option D: Parallel inheritance paths
Show hint

class C : public B where B : public A - three levels.

Show answer

Answer: B. Multiple inheritance levels (A->B->C)

Multilevel inheritance: inheritance chain where derived class becomes base for another. Example: class Animal { }; class Mammal : public Animal { }; class Dog : public Mammal { }. Dog inherits from Mammal, which inherits from Animal. Inheritance chain: Dog is-a Mammal is-a Animal. Member access: Dog can access public/protected members of both Mammal and Animal. Constructor: Dog() : Mammal() { } or Dog() : Mammal(), Animal() { } must call constructors in order (base first). Method override: each level can override or introduce methods. Virtual functions: enable polymorphic behavior across levels. Example: class Shape { virtual void draw() { } }; class 2DShape : public Shape { }; class Circle : public 2DShape { void draw() override { } }. Ambiguity: no diamond problem with multilevel (linear chain). Scope: searching for member starts at current class, then parent, then grandparent. Hidden: non-virtual methods hidden if overridden at any level. Complexity grows: deeper inheritance more complex, harder to understand. Best practice: limit depth (usually 3 levels max). Code reuse: inherit behavior progressively (general -> specific -> most specific). Polymorphism: common use case for heterogeneous collections (vector<Shape*>). Maintenance: changes to base affect all derived (for better or worse). Understanding multilevel inheritance important for hierarchical design.

468. What is hybrid inheritance in C++?

  1. Option A: Combining different inheritance types
  2. Option B: Only inheritance with interfaces
  3. Option C: Inheritance without virtual functions
  4. Option D: Temporary inheritance
Show hint

Mix of single, multiple, and multilevel inheritance in same hierarchy.

Show answer

Answer: A. Combining different inheritance types

Hybrid inheritance: combining multiple, single, and/or multilevel inheritance in complex hierarchy. Example structure: class A { }; class B : public A { }; class C : public A { }; class D : public B, public C { }; (multilevel + multiple + potential diamond). Diamond problem possible: if multiple paths lead to common base, virtual inheritance resolves. Real example: Graphics system - Shape (base), RectangleBase : public Shape, FillableBase : public Shape, FilledRectangle : public RectangleBase, public FillableBase. Complexity: increases significantly, harder to understand relationships. Benefits: model complex real-world hierarchies (e.g., objects with multiple capabilities). Challenges: ambiguity, virtual base initialization, maintenance. Virtual inheritance: class RectangleBase : virtual public Shape resolves diamond. Initialization order: virtual bases initialized before non-virtual. Methods: resolving which method to call requires careful analysis. Best practice: minimize, document clearly, consider composition instead. Example resolution: FilledRectangle calls both draw() from shape and fill() from fillable. Debugging: complex diamond problems hard to debug. Alternative: composition - FilledRectangle has Shape, Fill components instead. Modern design: hybrid inheritance rare in modern code, prefer composition. Understanding hybrid inheritance important for working with legacy systems.

469. What is multipath inheritance in C++?

  1. Option A: Single class accessed through multiple paths
  2. Option B: Multiple bases with common ancestor
  3. Option C: Multiple constructors
  4. Option D: Multiple inheritance levels
Show hint

Diamond problem - multiple paths to same base class.

Show answer

Answer: A. Single class accessed through multiple paths

Multipath inheritance (diamond inheritance): derived class reachable through multiple inheritance paths. Classic diamond: A is base, B inherits A, C inherits A, D inherits B and C. D has two paths to A (D->B->A and D->C->A). Problem without virtual: A instantiated twice, ambiguous member access, wasted memory. Without virtual base: D has two A sub-objects (one via B, one via C). Accessing: member of A ambiguous - d.member? comes from B's A or C's A? Solution: virtual inheritance. class B : virtual public A makes A virtual base. class C : virtual public A shared copy of A. With virtual: D has single A instance. Initialization: D() : B(), C(), A() explicitly initializes virtual base. Member access: d.member unambiguous. Virtual function calls resolved correctly. Example: Unix file system (File), Symbolic file (inherits File), Hard link (inherits File), Union (inherits both) - same file accessed through two paths. Real-world example: Multiple interface implementation. Cost: virtual inheritance adds indirection (pointer to virtual base), slightly slower access. Best practice: document virtual inheritance clearly, test thoroughly. Ambiguity without virtual: D d; d.member error (ambiguous). With virtual: works correctly. Avoid unless necessary: increases complexity. Alternative: use interfaces/mixins. Understanding multipath inheritance crucial for working with complex diamond hierarchies.

470. What are constructors and destructors in inheritance?

  1. Option A: Only derived classes have constructors
  2. Option B: Base and derived constructors both called, destructors in reverse order
  3. Option C: Only destructors matter in inheritance
  4. Option D: Inherited classes don't need constructors
Show hint

When Derived created, does Base also initialize? Destruction order?

Show answer

Answer: B. Base and derived constructors both called, destructors in reverse order

Constructor/destructor in inheritance: automatic chain calling, specific order. Constructor order: Base first, then Derived. Example: class Base { public: Base() { cout << "Base"; } }; class Derived : public Base { public: Derived() : Base() { cout << "Derived"; } }; Derived d; outputs "BaseDerived". Destructor order: Derived first, then Base (reverse of construction). ~Derived() called first, then ~Base() automatically. Destructor chain: ~Derived() { cout << "~Derived"; } calls ~Base() implicitly. Purpose: base resource cleanup after derived cleanup. Virtual destructor: important for polymorphism. Base *b = new Derived(); delete b; without virtual ~Base(), calls only ~Base(). With virtual: calls ~Derived() then ~Base(). Initialization list: Derived(int x) : Base(x), member(x) { }. Explicit base call: must chain if base has no default constructor. Constructor inheritance (C++11): using Base::Base; inherits base constructors. Delegating constructor: Derived() : Derived(0) { } calls another derived constructor. Example multilevel: class A { }; class B : public A { }; class C : public B { }; creating C calls A(), then B(), then C(). Destruction: ~C(), then ~B(), then ~A(). Virtual base: virtual base initialized before non-virtual bases. Parameterized base: must explicitly initialize. Exception safety: if derived constructor throws before base initialization, undefined. Best practice: explicit constructor chains, virtual destructors in polymorphic classes. Understanding constructor/destructor order crucial for resource management in inheritance.

471. What is operator overloading in C++?

NEC model set
  1. Option A: Defining a new operator
  2. Option B: Overriding an existing operator
  3. Option C: Changing the behaviour of an existing operator
  4. Option D: Changing the behaviour of new operator
Show hint

Overloading modifies how an existing operator works with different data types.

Show answer

Answer: C. Changing the behaviour of an existing operator

Operator overloading in C++ is the ability to redefine how existing operators (+, -, *, /, ==, etc.) work with user-defined types (classes). You cannot define entirely new operators (option 1 and 4 are incorrect). You don't simply override existing operators without a context (that's not what overloading means). Instead, operator overloading allows you to change the behavior of an existing operator to work with your custom classes. For example: class Complex { public: Complex operator+(const Complex& other) { ... } }; This redefines the '+' operator for Complex numbers. Benefits of operator overloading: (1) Makes code more intuitive and readable, (2) Allows natural syntax for custom types, (3) Maintains consistency with built-in types. Restrictions: Cannot overload (::, ., .*, ?:), must overload as member function (=, [], (), ->), cannot change operator precedence or associativity.

472. What happens when a derived class overrides a base class method?

NEC model set
  1. Option A: Base class method is called
  2. Option B: Derived class method replaces base class method
  3. Option C: Both methods run simultaneously
  4. Option D: Program throws an error
Show hint

Method overriding means derived version takes precedence over base version.

Show answer

Answer: B. Derived class method replaces base class method

When a derived class overrides a base class method, the derived class method replaces base class method in normal polymorphic behavior. Method overriding mechanism: (1) Derived class defines method with same signature as base, (2) When called on derived object - Derived version executes, (3) Allows customization - Different behavior in derived class, (4) Fundamental to polymorphism. How overriding works: (1) Base class defines virtual method, (2) Derived class redefines with same signature, (3) Polymorphic call through base pointer/reference - Calls derived version, (4) Determined at runtime - Dynamic binding. Example: class Base { virtual void func() { cout << "Base"; } }; class Derived : public Base { void func() { cout << "Derived"; } }; Base *ptr = new Derived(); ptr->func(); // Outputs "Derived". Access mechanisms: (1) Polymorphic (through base ptr/ref) - Calls derived version, (2) Direct - obj.func() calls derived if obj is derived type, (3) Explicit base call - Base::func() from derived class. Virtual requirement: (1) Base method must be virtual - To enable overriding, (2) Non-virtual - Compile-time binding, base version called, (3) override keyword - C++11+ marks intent. Different from overloading: (1) Overloading - Same name, different parameters, (2) Overriding - Same name, same parameters, inheritance. Special methods: (1) Destructors - Should be virtual if inheritance used, (2) Constructors - Cannot be virtual, each class has own, (3) Operators - Can be overridden. Both running - No, one or the other. Errors - No, valid OOP pattern. This is core polymorphism concept.

473. When a derived class inherits from a base class, which constructor is executed first?

Recalled from Jan 2026 exam
  1. Option A: Derived class constructor only
  2. Option B: Base class constructor, then derived class constructor
  3. Option C: Derived class constructor, then base class constructor
  4. Option D: Both constructors are executed simultaneously
Show hint

Constructor execution follows a specific order in inheritance. What is the sequence?

Show answer

Answer: B. Base class constructor, then derived class constructor

When a derived class inherits from a base class, the base class constructor is executed first, then the derived class constructor. This order ensures that the base class object is properly initialized before the derived class initializes its additional members. If the base class constructor isn't called explicitly, the compiler calls a default or implicit constructor. This initialization order is important because the derived class might depend on proper initialization of inherited members. The reverse order (destructors) applies in reverse - derived class destructor first, then base class destructor.

474. What is the main advantage of hybrid inheritance?

Recalled from Jan 2026 exam
  1. Option A: Code reusability
  2. Option B: Reduced memory usage
  3. Option C: Faster compilation
  4. Option D: Simpler syntax
Show hint

Hybrid inheritance combines multiple inheritance types. What's the primary benefit?

Show answer

Answer: A. Code reusability

The main advantage of hybrid inheritance is code reusability. Hybrid inheritance combines multiple inheritance types (single, multilevel, multiple, hierarchical) to leverage features from multiple base classes. This allows a derived class to inherit code and functionality from multiple sources, reducing code duplication and promoting modularity. With proper design using hybrid inheritance, developers can build complex class hierarchies that maximize code reuse. While hybrid inheritance is powerful, it can introduce complexity (diamond problem) if not carefully designed. Languages like C++ support hybrid inheritance; some languages like Java restrict it to avoid these complications.

475. Which operator cannot be overloaded in C++?

  1. Option A: && and ||
  2. Option B: :: and ->
  3. Option C: + and -
  4. Option D: All of the above
Show answer

Answer: B. :: and ->

476. Which of the following operators can be overloaded in C++?

  1. Option A: +
  2. Option B: =
  3. Option C: []
  4. Option D: All of the above
Show answer

Answer: D. All of the above

477. Which access specifier allows a derived class to access the protected members of its base class?

  1. Option A: public
  2. Option B: private
  3. Option C: protected
  4. Option D: friend
Show answer

Answer: C. protected

478. Which of the following operators can be overloaded to provide custom member access behavior?

  1. Option A: .
  2. Option B: ->
  3. Option C: ::
  4. Option D: :
Show answer

Answer: B. ->

3.5 Pure virtual functions and file handling

10 questions · ACtE0305

479. Virtual functions are accessed through?

  1. Option A: Variable
  2. Option B: Array
  3. Option C: Object
  4. Option D: Object pointers
Show hint

Polymorphism works through pointers/references.

Show answer

Answer: D. Object pointers

Virtual functions are accessed through object pointers or references to enable polymorphic behavior.

480. What is purpose of 'override' keyword in C++?

  1. Option A: Indicate function is virtual
  2. Option B: Indicate function is override of virtual function
  3. Option C: Indicate pure virtual function
  4. Option D: None of the above
Show hint

Ensures correct virtual function overriding.

Show answer

Answer: B. Indicate function is override of virtual function

'override' keyword explicitly declares that a function overrides a virtual base class function, catching errors at compile time.

481. What OOP concept allows different classes to be treated as common base?

  1. Option A: Encapsulation
  2. Option B: Inheritance
  3. Option C: Polymorphism
  4. Option D: Abstraction
Show hint

Many forms, one interface.

Show answer

Answer: C. Polymorphism

Polymorphism allows objects of different classes to be treated through common base class interface.

482. What are virtual functions in C++?

  1. Option A: Functions that don't have implementation
  2. Option B: Functions supporting runtime polymorphism through dynamic dispatch
  3. Option C: Functions existing only at compile time
  4. Option D: Functions shared between objects
Show hint

virtual void func() enables derived override, correct version called at runtime.

Show answer

Answer: B. Functions supporting runtime polymorphism through dynamic dispatch

Virtual functions: enable runtime polymorphism, correct derived version called through base pointer/reference. Declaration: virtual void func() { }. Override: derived redefines with same signature. Dynamic dispatch: selecting method based on actual object type, not pointer type. Example: class Shape { virtual void draw() { } }; class Circle : public Shape { void draw() override { cout << "Circle"; } }; Shape *s = new Circle(); s->draw() calls Circle::draw(), not Shape::draw(). V-table: compiler creates virtual method table for each class. Virtual call: looks up v-table entry, calls appropriate function. Cost: pointer dereference (slight performance hit). Non-virtual: call resolved at compile time (fast). Pure virtual: virtual void func() = 0; abstract function. Abstract class: cannot instantiate, must override pure virtuals in derived. Final (C++11): virtual void func() final; prevents further overriding. Override (C++11): void func() override; ensures overriding virtual function (compiler error if not). Example: class Animal { virtual void sound() { } }; class Dog : public Animal { void sound() override { cout << "Woof"; } }. Polymorphic call: vector<Animal*> animals; for(auto a : animals) a->sound() calls appropriate version. Without virtual: all calls resolve to Shape::draw() (no polymorphism). Inheritance hierarchy: virtual defined at any level works through whole hierarchy. Base class pointer: can point to any derived object, virtual ensures correct behavior. Virtual destructor: essential for polymorphism (discussed separately). Understanding virtual functions fundamental to OOP and polymorphism.

483. What is dynamic binding in C++?

  1. Option A: Binding variables to types at runtime
  2. Option B: Resolving virtual function calls at runtime based on actual object type
  3. Option C: Binding memory dynamically
  4. Option D: Linking libraries at runtime
Show hint

vs static binding (compile-time), dynamic binding checks actual object type.

Show answer

Answer: B. Resolving virtual function calls at runtime based on actual object type

Dynamic binding: runtime resolution of method calls based on actual object type, not apparent type. Enabled by: virtual functions + polymorphism. Static binding: compile-time resolution (normal functions). Example: class Animal { public: virtual void speak() { } }; class Dog : public Animal { public: void speak() { cout << "Woof"; } }; Animal *a = new Dog(); a->speak() uses dynamic binding, calls Dog::speak(). Without virtual: static binding, calls Animal::speak(). How it works: (1) Base pointer/reference holds derived object. (2) Virtual function call. (3) Compiler generates code to look up v-table at runtime. (4) Finds correct function for actual type. (5) Calls derived implementation. V-table lookup: small overhead (pointer dereference, array lookup). Multiple dispatch: single dispatch (C++) vs multiple dispatch (Visitor pattern). Performance: slightly slower than static (1-3% typically). Optimization: compiler may devirtualize if type known. Example without dynamic binding: Shape *s = new Circle(); if(typeid(*s)==typeid(Circle)) ((Circle*)s)->draw() - ugly and slow. With dynamic binding: s->draw() - clean and still polymorphic. Polymorphic collections: vector<Shape*> shapes; shapes.push_back(new Circle()); shapes.push_back(new Square()); for(auto s : shapes) s->draw() works correctly. Design pattern: enables extensible code (new derived classes without changing code using base). Cost-benefit: small performance cost for huge design flexibility. Understanding dynamic binding crucial for polymorphic design.

484. What is the difference between ifstream and ofstream in C++?

NEC model set
  1. Option A: ifstream is used for input, while ofstream is used for output
  2. Option B: ofstream is used for input, while ifstream is used for output
  3. Option C: both are used as input
  4. Option D: both are used as output
Show hint

'i' = input, 'o' = output. The prefix clearly indicates the direction of data flow.

Show answer

Answer: A. ifstream is used for input, while ofstream is used for output

In C++, ifstream and ofstream are file stream classes from the <fstream> library: (1) ifstream (input file stream) - Used for reading data from files. Opens files in input mode by default. (2) ofstream (output file stream) - Used for writing data to files. Opens files in output mode by default. Additional file stream classes: (3) fstream - Can be used for both input and output operations, requiring explicit specification of mode. Usage examples: ifstream infile("input.txt"); // Opens for reading, ofstream outfile("output.txt"); // Opens for writing. These classes inherit from basic_istream and basic_ostream respectively. They automatically handle file opening and closing (destructor closes file). They support operators (>> for input, << for output) making file I/O similar to console I/O. Using the appropriate stream class improves code clarity and prevents accidental operations on files.

485. How do you declare a virtual function in C++?

NEC model set
  1. Option A: virtual void func();
  2. Option B: void virtual func();
  3. Option C: void func() virtual;
  4. Option D: void func() : virtual;
Show hint

Virtual keyword comes before the return type. What's the correct syntax?

Show answer

Answer: A. virtual void func();

Virtual functions are declared using the 'virtual' keyword before the return type: 'virtual void func();'. The virtual keyword enables dynamic (runtime) polymorphism. When a virtual function is called through a pointer or reference, the appropriate overridden version in the derived class is executed. Virtual functions must be member functions and cannot be static or friends. They are fundamental to implementing polymorphic behavior in C++.

486. Which file stream flag in C++ is used to position the file pointer at the start of the file?

Recalled from Jan 2026 exam
  1. Option A: ios::first
  2. Option B: ios::beg
  3. Option C: ios::start
  4. Option D: ios::begin
Show hint

File seeking position flags. What flag positions at the beginning?

Show answer

Answer: B. ios::beg

The ios::beg file stream flag in C++ is used to position the file pointer at the start of the file. This flag is used with the seek() function: file.seekg(0, ios::beg) positions the pointer at the file's beginning. ios::end positions at the end. ios::cur positions relative to current location. These flags are fundamental to file I/O operations for random access. They work with both input (seekg) and output (seekp) operations.

487. Which C++ header file must be included to use the ifstream class for file input?

Recalled from Jan 2026 exam
  1. Option A: <iostream>
  2. Option B: <fstream>
  3. Option C: <stdio.h>
  4. Option D: <iomanip>
Show hint

File stream classes (ifstream, ofstream, fstream) are in which header?

Show answer

Answer: B. <fstream>

The <fstream> header file must be included to use the ifstream class for file input in C++. fstream stands for file stream and contains the file stream classes: ifstream (input), ofstream (output), and fstream (both). iostream contains console I/O classes (cin, cout). stdio.h is C-style file I/O. iomanip provides formatting manipulators. Including <fstream> provides all necessary file I/O functionality.

488. Can a virtual function be inline in C++?

  1. Option A: When the function is used in only one place in the program
  2. Option B: No, virtual functions cannot be inline in C++
  3. Option C: Yes, as long as it is defined with the "inline" keyword only
  4. Option D: It depends on the compiler
Show answer

Answer: B. No, virtual functions cannot be inline in C++

3.6 Generic programming and exception handling

16 questions · ACtE0306

489. How is exception handling implemented in C++?

  1. Option A: Using Exception keyword
  2. Option B: Using try-catch block
  3. Option C: Using Exception block
  4. Option D: Using Error handling schedules
Show hint

Typical exception handling structure.

Show answer

Answer: B. Using try-catch block

C++ exception handling uses try-catch-throw mechanism where try contains code that might throw, catch handles thrown exceptions.

490. What is throw keyword in C++?

  1. Option A: Catches exceptions
  2. Option B: Throws exceptions
  3. Option C: Declares exceptions
  4. Option D: Handles errors
Show hint

Initiates exception handling.

Show answer

Answer: B. Throws exceptions

throw keyword throws an exception, transferring control to nearest catch block.

491. What is exception handling in C++ - try, catch, throw?

  1. Option A: Error prevention mechanisms
  2. Option B: Mechanism for managing errors and abnormal conditions
  3. Option C: Debugging technique
  4. Option D: Memory management method
Show hint

try block executes, throw propagates error, catch handles.

Show answer

Answer: B. Mechanism for managing errors and abnormal conditions

Exception handling: mechanism to gracefully handle errors and exceptional conditions. Three components: (1) Try: wraps code that might throw. (2) Catch: handles thrown exception. (3) Throw: signals error, passes control to catch. Syntax: try { /* code */ } catch(ExceptionType e) { /* handle */ }. Example: try { int x = stoi("abc"); } catch(invalid_argument e) { cout << "Invalid"; }. Multiple catch: try { /* code */ } catch(DivideByZero e) { } catch(OutOfRange e) { }. Catch-all: catch(...) { } catches any exception. Throw: throw std::runtime_error("Error message"); creates and throws exception object. Exception propagation: unhandled exception propagates up call stack. Example: void func() { throw runtime_error("Error"); } main calls func, error propagates. Standard exceptions: runtime_error, invalid_argument, out_of_range, bad_alloc, etc. Custom exceptions: class MyException : public std::exception { }. What throws: throw MyException("Custom error"). Cleanup: destructors called during unwinding (RAII cleanup). Const &: catch(const std::exception& e) preferred (polymorphic handling). STL containers: throw out_of_range, bad_alloc. Re-throw: catch { /* handle */ throw; } re-throws original exception. Nested try-catch: try inside catch block. Exception safety: noexcept void func() noexcept; specifies no exceptions. Benefits: error handling decoupled from normal flow, clear error codes (exception type). Disadvantages: overhead (performance), complex control flow. Best practice: throw early (detect errors quickly), catch specific exceptions, clean up in destructors. Understanding exception handling essential for robust error management.

492. What are function templates in C++?

  1. Option A: Template design for functions
  2. Option B: Generic functions working with multiple types
  3. Option C: Functions with template parameters
  4. Option D: Pre-defined function patterns
Show hint

template<typename T> T max(T a, T b) - one function for all types.

Show answer

Answer: B. Generic functions working with multiple types

Function templates: generic functions accepting type parameters, one template generates multiple concrete functions. Syntax: template<typename T> T func(T a, T b) { /* implementation */ }. Usage: int x = max(5, 3); double y = max(3.5, 2.1); string z = max("abc", "xyz"); one template, three specializations generated. Type deduction: compiler deduces T from arguments (or explicitly max<int>(5, 3)). Multiple type parameters: template<typename T, typename U> T func(T a, U b) { }. Non-type parameters: template<int N> void func() { }; fixed N at compile-time. Default type parameters: template<typename T = int> T func() { }. Constraints: template applies to all types unless constrained. Specialization: explicit specialization for specific type. Example: template<> string func<string>(string a, string b) { special handling }. Advantages: code reuse across types, type-safe, compiler optimizations. Disadvantages: compilation slower (instantiation), error messages complex, larger executable. Instantiation: compiler creates function for each type used. Example: max template instantiated for int, double, string separately. Performance: no runtime overhead (generated at compile-time). SFINAE: substitution failure is not an error (advanced). Concepts (C++20): specify type requirements. Example swap template: template<typename T> void swap(T& a, T& b) { T t=a; a=b; b=t; }. STL: all STL algorithms templates (sort, find, transform). Understanding function templates essential for generic programming.

493. What are class templates in C++?

  1. Option A: Template design for classes
  2. Option B: Generic classes accepting type parameters
  3. Option C: Classes with template methods
  4. Option D: Pre-defined class patterns
Show hint

template<typename T> class Container { T data; }; Container<int>, Container<string>, etc.

Show answer

Answer: B. Generic classes accepting type parameters

Class templates: generic classes accepting type parameters, creating type-specific classes. Syntax: template<typename T> class MyClass { private: T data; public: void set(T val) { data = val; } T get() { return data; } }. Usage: MyClass<int> intObj; MyClass<string> strObj; MyClass<double> doubleObj. Instantiation: compiler generates three different classes (MyClass<int>, MyClass<string>, etc.). Member functions: all members work with type T. Multiple type parameters: template<typename T, typename U> class Pair { T first; U second; }. Static members: each instantiation has own static member. Example: vector, list, map, set are class templates. Specialization: explicit specialization for specific type. Example: template<> class MyClass<string> { special implementation }. Partial specialization: template<typename T> class MyClass<T*> { /* pointer specialization */ }. Inheritance: class Derived : public MyClass<int> { }. Constraints: template<typename T> requires Addable<T> class MyClass (C++20). Advantages: strong type safety, no void pointer casts, flexibility. Disadvantages: code bloat (separate code for each type), longer compilation, complex error messages. STL containers: vector<T>, list<T>, set<T>, map<K,V> are class templates. Default type: template<typename T = int> class MyClass. Non-type parameters: template<typename T, int N> class Array { T data[N]; }. Understanding class templates fundamental to modern C++ and generic containers.

494. What is the Standard Template Library (STL) in C++?

  1. Option A: Library of standard C++ functions
  2. Option B: Collection of generic containers, algorithms, and iterators
  3. Option C: Built-in data structure library
  4. Option D: Standard function templates
Show hint

vector, list, map, sort, find, for_each - these are STL components.

Show answer

Answer: B. Collection of generic containers, algorithms, and iterators

STL: provides generic, reusable components. Three main parts: (1) Containers: data structures (vector, list, deque, set, map, etc.). (2) Algorithms: operations on containers (sort, find, transform, etc.). (3) Iterators: generalized pointers for container traversal. Containers: sequential (vector, list, deque), associative (set, map, multiset, multimap), unordered (unordered_set, unordered_map). Algorithms: sorting (sort, stable_sort), searching (find, binary_search, lower_bound), modification (transform, copy), numeric (accumulate, inner_product). Iterators: input, output, forward, bidirectional, random access. Example: vector<int> v = {3,1,4,1,5}; sort(v.begin(), v.end()); find(v.begin(), v.end(), 4). Advantages: proven, optimized implementations, consistency across containers, flexibility. Iterator abstraction: algorithms work with any container. Example: sort works on vector, deque, arrays (with different iterators). Functional objects: std::less, std::greater for custom comparison. Lambda expressions: algorithm callbacks. Example: sort(v.begin(), v.end(), [](int a, int b) { return a > b; }) sorts descending. Performance: optimized implementations (O(n log n) sort), cache-friendly. Containers: O(1) or O(log n) operations. Learning curve: steep for complex usage, but mastering STL essential for modern C++. Understanding STL fundamental to effective C++ programming.

495. What are iterators in STL?

  1. Option A: Functions that iterate
  2. Option B: Generalized pointers for container traversal
  3. Option C: Loop constructs
  4. Option D: Container indices
Show hint

v.begin(), v.end(), ++it, *it - iterator operations.

Show answer

Answer: B. Generalized pointers for container traversal

Iterators: generalized pointers allowing access and traversal of container elements. Categories: (1) Input: read-only, single-pass. (2) Output: write-only, single-pass. (3) Forward: read-write, single-pass. (4) Bidirectional: read-write, bidirectional (++, --). (5) Random access: read-write, random (+=, -=, [i]). Operations: *it (dereference), ++it (increment), it->member (member access). Example: vector<int> v = {1,2,3}; for(auto it = v.begin(); it != v.end(); ++it) cout << *it;. Range-based for: for(int x : v) simpler, equivalent. Type: vector<int>::iterator, list<int>::iterator (different types). Const iterator: const_iterator read-only, reverse_iterator backwards. Algorithms: work with iterators. Example: find(v.begin(), v.end(), 2) finds element 2. Distance: distance(it1, it2) steps between iterators (random access O(1), bidirectional O(n)). Advance: advance(it, n) moves iterator n positions. Invalid iterators: after erase, capacity change invalidates (container dependent). Performance: O(1) dereference, O(1) increment (forward+). Container choice affects iterator type. Example: vector (random), list (bidirectional), set (bidirectional). Advantages: algorithm abstraction (same algorithm works on any container), clean syntax. Disadvantages: confusing at first, need to understand category constraints. Invalidation rules: erase invalidates following iterators in vector, all in list. Understanding iterators essential for STL and generic algorithms.

496. What is the difference between containers in STL?

  1. Option A: All containers identical
  2. Option B: Different data structures optimized for different use cases
  3. Option C: Only difference is template type parameter
  4. Option D: Containers for different industries
Show hint

vector vs list vs set - what are tradeoffs?

Show answer

Answer: B. Different data structures optimized for different use cases

STL Containers: different data structures, different performance characteristics. vector<T>: dynamic array, O(1) random access, O(1) push_back, O(n) insert/erase middle. Use: fast access, append. list<T>: doubly-linked list, O(n) access, O(1) insert/erase anywhere, bidirectional. Use: frequent insertion/deletion. deque<T>: double-ended queue, O(1) access/push_pop front-back, O(n) insert/erase middle. Use: queues. set<T>: ordered tree, O(log n) operations, unique elements. Use: sorted unique collection. map<K,V>: ordered tree, O(log n) lookup/insert/erase, key-value pairs. Use: associative array. unordered_set<T>: hash table, O(1) average operations, unordered. Use: fast unique lookup. unordered_map<K,V>: hash table, O(1) average lookup. Use: fast dictionary. multiset<T>/multimap<K,V>: allow duplicates. priority_queue<T>: heap, O(1) top, O(log n) push/pop. Use: priority queues. Stack (LIFO): vector/deque/list adapter, LIFO access. Queue (FIFO): vector/deque/list adapter, FIFO access. Choice criteria: (1) Access pattern (random vs sequential). (2) Insertion/deletion (frequent?). (3) Search (ordered vs fast). (4) Memory (linked lists use more). Example: log file processing (vector append), network packet processing (queue), priority events (priority_queue), cache (unordered_map). Performance comparison: access time, insertion time, deletion time, memory overhead. Selecting container crucial for application performance. Understanding container tradeoffs essential for algorithm optimization.

497. What are STL algorithms?

  1. Option A: Steps for solving problems
  2. Option B: Generic functions operating on containers via iterators
  3. Option C: Container implementation details
  4. Option D: Mathematical calculations
Show hint

sort, find, transform, copy - operations on containers.

Show answer

Answer: B. Generic functions operating on containers via iterators

STL algorithms: generic functions performing operations on container ranges via iterators. Categories: (1) Sorting: sort(), stable_sort(), partial_sort(), nth_element(). (2) Searching: find(), binary_search(), find_if(), lower_bound(), upper_bound(). (3) Mutation: transform(), fill(), replace(), shuffle(). (4) Removal: remove(), unique(). (5) Numeric: accumulate(), inner_product(), partial_sum(). (6) Iteration: for_each(), transform(). Examples: vector<int> v = {3,1,4,1,5,9}; sort(v.begin(), v.end()). auto it = find(v.begin(), v.end(), 4); transform(v.begin(), v.end(), v.begin(), [](int x) { return x*2; }). Advantages: (1) Container-independent (work with any container). (2) Efficient implementations. (3) Consistent interface. (4) Composable. Predicates: custom comparison/condition. Example: sort(v.begin(), v.end(), greater<int>()) descending. Lambda expressions: inline predicates. Example: find_if(v.begin(), v.end(), [](int x) { return x > 3; }). Non-modifying: find, count, search. Modifying: sort, reverse, rotate, shuffle. Performance: sort O(n log n), find O(n), binary_search O(log n). Ranges (C++20): easier syntax, same algorithms. Understanding algorithms enables powerful generic code. Writing efficient algorithms crucial for performance.

498. What is multiple exception handling in C++?

  1. Option A: Throwing multiple exceptions
  2. Option B: Catching different exception types in separate catch blocks
  3. Option C: Handling exceptions multiple times
  4. Option D: Exceptions with many parameters
Show hint

try { } catch(TypeA) { } catch(TypeB) { } catch(...) { }

Show answer

Answer: B. Catching different exception types in separate catch blocks

Multiple exception handling: try block with multiple catch blocks for different exception types. Syntax: try { /* code */ } catch(ExceptionType1 e) { /* handle type 1 */ } catch(ExceptionType2 e) { /* handle type 2 */ } catch(...) { /* handle any */ }. Order matters: catch blocks checked in order, first matching catches. Example: try { int x = stoi("abc"); int y = 10/0; } catch(invalid_argument& e) { cout << "Invalid arg: " << e.what(); } catch(exception& e) { cout << "General error: " << e.what(); }. Specific to general: more specific exceptions first (derived class before base). Exception hierarchy: std::exception base, runtime_error, invalid_argument, out_of_range derived. Polymorphic catch: catch(const std::exception& e) catches any standard exception. What(): get error message string. Custom exceptions: class MyError : public std::exception { public: const char* what() const override { return "My error"; } }. Multiple sources: different operations throw different exceptions. Example: parsing code - invalid_argument, encoding error, file read - io_error. Catch-all: catch(...) { } last resort, catches anything (even non-standard). Re-throw: catch(MyException& e) { log(e); throw; } re-throws original. Chaining: catch one exception type, throw another. Example: catch(FileNotFound& e) { throw ProcessingError(e); }. Exception safety: strong guarantee (all-or-nothing), basic guarantee (some recovery). Best practice: specific catches first, catch-all last or omit, throw appropriate types. Understanding multiple exception handling essential for robust error management.

499. What is a class template in C++?

NEC model set
  1. Option A: A class that can be used to create objects of different types
  2. Option B: A function that can be used to create objects of different types
  3. Option C: A variable that can be used to create objects of different types
  4. Option D: A character that can be used to create objects of different types
Show hint

Templates enable generic programming. A template class can work with any data type.

Show answer

Answer: A. A class that can be used to create objects of different types

A class template in C++ is a blueprint for creating classes that can work with any data type. It allows you to define a generic class where the data type is parameterized. Key concepts: (1) Templates use template parameters (usually template<typename T>), (2) You can use the parameter T as any data type within the class, (3) Instantiation creates specific classes for each data type used. Example: template<typename T> class Stack { private: T data[100]; }; This creates a Stack that works with any type. Usage: Stack<int> intStack; Stack<double> doubleStack; Both are created from the same template. Benefits: (1) Code reusability across different data types, (2) Type safety (templates are type-checked at compile time), (3) No runtime overhead. Class templates are fundamental to the Standard Template Library (STL) which provides containers like vector, list, map using templates. This differs from function templates (which template functions) or variable templates (C++14).

500. What happens if an exception is thrown but not caught?

NEC model set
  1. Option A: Program continues normally
  2. Option B: The exception is ignored
  3. Option C: Program crashes or terminates
  4. Option D: The exception is logged and ignored
Show hint

Unhandled exceptions cause the program to stop. What happens to the program?

Show answer

Answer: C. Program crashes or terminates

If an exception is thrown but not caught by any try-catch block, the program terminates or crashes. The exception propagates up the call stack looking for a handler. If no handler is found, the program crashes with an error. In some systems, an uncaught exception handler might log the error before terminating. Proper exception handling requires using try-catch blocks to gracefully handle errors and prevent program termination.

501. What is an exception in object-oriented programming?

Recalled from Jan 2026 exam
  1. Option A: A special function
  2. Option B: A type of inheritance
  3. Option C: A method
  4. Option D: A class
Show hint

Exceptions are abnormal conditions during program execution. What are they?

Show answer

Answer: A. A special function

An exception in object-oriented programming is a special function or mechanism that handles abnormal conditions during program execution. When an error or exceptional situation occurs, an exception is thrown, interrupting normal program flow. The program then jumps to exception handlers (catch blocks) that deal with the problem. Exceptions allow graceful error handling instead of program crashes. They're not a type of inheritance, method, or regular class, but rather a control flow mechanism. Exception handling improves program robustness and maintainability by separating error handling code from normal logic.

502. In the Standard Template Library (STL), what do containers primarily hold?

Recalled from Jan 2026 exam
  1. Option A: Functions and algorithms
  2. Option B: Data elements and their organization
  3. Option C: Iterators and pointers only
  4. Option D: Memory addresses
Show hint

STL containers are data structures. What do they store and manage?

Show answer

Answer: B. Data elements and their organization

In the Standard Template Library (STL), containers primarily hold data elements and their organization. Containers are template classes that manage collections of data with different organizational structures (vector, list, queue, stack, map, etc.). Each container type organizes data differently to optimize specific operations. Containers provide iterators for traversing elements and algorithms operate on container data through iterators. Functions and algorithms are separate STL components. Iterators are access mechanisms, not what containers hold. Memory addresses are implementation details, not the primary purpose.

503. Which of the following is true about default arguments and templates?

  1. Option A: Default arguments are not allowed in templates
  2. Option B: Default arguments can be used in templates, but only for one parameter
  3. Option C: Default arguments can be used in templates for any number of parameters
  4. Option D: Default arguments in templates must be the same for all instantiations
Show answer

Answer: C. Default arguments can be used in templates for any number of parameters

504. Containers are contained within?

Past question
  1. Option A: Function
  2. Option B: String
  3. Option C: Containers
  4. Option D: Elements
Show hint

Containers can be nested inside other containers. What holds multiple items?

Show answer

Answer: C. Containers

Containers are contained within Containers (nested containers). Container Concept: (1) Data structures that hold multiple items, (2) Examples: arrays, lists, maps, sets, (3) Can contain primitive types or other containers. Nesting in Containers: (1) Containers can hold other containers, (2) Example: vector of vectors (2D array), (3) Example: map of lists (key→list), (4) Unlimited nesting levels possible. Nested Container Examples: (1) Vector<Vector<int>> - 2D matrix, (2) Map<String, List<String>> - Each key maps to list, (3) Set<Vector<int>> - Set of vectors, (4) List<Map<int, String>> - List of maps. C++ STL Containers: (1) Sequence containers - vector, list, deque, (2) Associative - map, set, multimap, (3) Unordered - unordered_map, unordered_set. Why Nesting Matters: (1) Represents hierarchical data, (2) Models real-world structures, (3) Solves complex problems, (4) Enables powerful algorithms. Other Options Explanation: (1) Function - Functions are not containers for other functions (in standard sense), (2) String - String contains characters, not containers, (3) Elements - Elements are items in containers, not containers themselves. Practical Applications: (1) File systems - Directories within directories, (2) XML/JSON - Nested structures, (3) Graphs - Containers of nodes/edges, (4) Game development - Nested game objects. Memory Considerations: (1) Nested containers use more memory, (2) Deep nesting can cause stack overflow, (3) Performance implications with large data. This demonstrates data structure composition.

Questions from bibhushansaakha/MCQ (MIT License, © 2024 Bibhushan Saakha) and SamirWagle/NECPrep. Exact duplicates are shown once. Where the source’s answer is missing, repeated, or disagrees between copies, the question carries a note. Questions are sorted into the official NEC syllabus topics; a few that sit between two topics may be filed under either.