Cherreads

Chapter 6 - C and C++

Part 1: The C Language (Rapid Fire)Keywords & Basics

Q: What is the auto keyword in C?

A: It is the default storage class for local variables. Rarely used explicitly.

Q: What is the register keyword?

A: Suggests the compiler store the variable in a CPU register for faster access. You cannot get the address (&) of a register variable.

Q: What is signed vs unsigned?

A: signed uses one bit for the sign (+/-). unsigned uses all bits for magnitude, effectively doubling the positive range.

Q: What is typedef?

A: It creates an alias for an existing data type (e.g., typedef unsigned long ulong;) to improve code readability.

Q: What is an enum?

A: A user-defined type consisting of a set of named integer constants (e.g., enum Color { RED, GREEN };).

Q: What is the size of an empty struct in C?

A: It is technically undefined (or 0) in C, but in C++, the size of an empty struct/class is 1 byte to ensure unique addresses.

Q: What is a token in C?

A: The smallest individual unit in a program (keywords, identifiers, constants, strings, operators).

Q: What is the scope of a function?

A: By default, functions have extern scope (global). If marked static, they are limited to the defining file.

Q: What is the return type of printf?

A: It returns an int: the total number of characters successfully written to the output.

Q: What is the return type of scanf?

A: It returns an int: the number of items successfully read and assigned.

Q: What is type promotion?

A: Implicitly converting a smaller type (like char or short) to int during arithmetic operations.

Q: What is the difference between i++ and ++i?

A: i++ (Post-increment) uses the value then increments. ++i (Pre-increment) increments then uses the value.

Q: What are bitwise operators?

A: Operators that manipulate individual bits: & (AND), | (OR), ^ (XOR), ~ (NOT), << (Left Shift), >> (Right Shift).

Q: How do you check if a number is odd using bitwise?

A: if (num & 1) returns true for odd numbers.

Q: How do you check if a number is a power of 2?

A: if ((n > 0) && ((n & (n - 1)) == 0))

Q: What is Short Circuit evaluation?

A: In A && B, if A is false, B is not evaluated. In A || B, if A is true, B is not evaluated.

Pointers & Arrays (The "Tricky" Stuff)

Q: What is *ptr++ vs ++*ptr?

A: *ptr++ returns the value, then moves the pointer. ++*ptr increments the value pointed to.

Q: What is a generic pointer?

A: A void*. It can hold the address of any type but must be cast before dereferencing.

Q: What is a Null Pointer?

A: A pointer that points to address 0 ((void*)0). It is used to signify "no value".

Q: What is a Wild Pointer?

A: An uninitialized pointer that points to an arbitrary memory location (dangerous).

Q: Can you subtract two pointers?

A: Yes, if they point to elements of the same array. The result is the number of elements between them (ptrdiff_t).

Q: Can you add two pointers?

A: No, adding addresses makes no logical sense in memory mapping.

Q: What is an Array of Pointers?

A: int *arr[5]; - An array where every element is a pointer to an integer.

Q: What is a Pointer to an Array?

A: int (*ptr)[5]; - A single pointer that points to an entire array of 5 integers.

Q: What is argv and argc?

A: argc: Argument count. argv: Argument vector (array of strings). Used for Command Line Arguments.

Q: Is arr same as &arr?

A: Value-wise, yes (same address). Type-wise, no. arr is int* (first element), &arr is int(*)[size] (whole array).

Q: What is a near, far, and huge pointer?

A: Legacy concepts (16-bit DOS). Near = 16-bit offset. Far = Segment+Offset. Huge = Normalized Far pointer. Not used in modern systems.

Q: How to free a block of memory without free()?

A: You can use realloc(ptr, 0).

Q: What happens if you free a pointer twice?

A: "Double Free" error. It corrupts the heap management data structures and usually crashes the program.

Q: What is a flexible array member?

A: C99 feature: An array [] at the end of a struct allows allocating variable-sized structures.

Advanced C & System

Q: What is #pragma pack(1)?

A: It forces the compiler to align structure members on 1-byte boundaries (disabling padding).

Q: What is #define?

A: A preprocessor directive to create macros or constants.

Q: What is the # and ## operator in macros?

A: # converts an argument to a string. ## concatenates two tokens.

Q: What is a segmentation fault (segfault)?

A: Occurs when a program tries to access memory it doesn't have permission to access (e.g., dereferencing NULL).

Q: What is the difference between Text and Binary files?

A: Text files process newlines (\n) and encoding. Binary files read raw bytes exactly as stored.

Q: What is fseek()?

A: Moves the file pointer to a specific location in a file.

Q: What is Little Endian vs Big Endian?

A: Little: LSB stored at lowest address. Big: MSB stored at lowest address.

Q: What is setjmp and longjmp?

A: The C equivalent of "throw/catch". It allows jumping across functions (non-local goto).

Q: What is memory layout of a C program?

A: Text (Code), Data (Global/Static), Heap (Dynamic), Stack (Local/Functions).

Q: What is a constant pointer to constant data?

A: const int * const ptr; - Neither the pointer address nor the value can be changed.

Part 2: C++ Language (Rapid Fire)OOP & Core

Q: What is an Object?

A: An instance of a class that holds state (variables) and behavior (methods).

Q: What is Encapsulation?

A: Wrapping data and functions into a single unit (class) and restricting access using modifiers.

Q: What is Abstraction?

A: Hiding complex implementation details and showing only the essential features to the user.

Q: What is Polymorphism?

A: The ability of a message to be displayed in more than one form (Compile-time vs Runtime).

Q: What is Inheritance?

A: A mechanism where one class acquires the properties and behaviors of another class.

Q: What is struct vs class inheritance default?

A: struct inherits public by default. class inherits private by default.

Q: What is Multiple Inheritance?

A: A class derived from more than one base class (class C : public A, public B).

Q: What is a friend class?

A: A class that can access the private and protected members of another class.

Q: Can constructors be virtual?

A: No, because the VTABLE is not initialized until the constructor finishes executing.

Q: Can destructors be virtual?

A: Yes, and they should be in base classes to ensure proper cleanup of derived objects.

Q: What is an explicit constructor?

A: A constructor marked explicit prevents implicit type conversion (e.g., Class c = 5;).

Q: What is this?

A: A const pointer pointing to the current object instance.

Q: What is static member function?

A: A function that belongs to the class, not an object. It cannot access this or non-static members.

Q: What is Method Hiding?

A: If a child defines a non-virtual method with the same name as the parent, the parent's method is hidden.

Q: What is slicing?

A: When a derived object is assigned to a base object by value, the derived part is "sliced" off.

Q: What is a local class?

A: A class defined inside a function. It cannot have static data members.

Q: What is a nested class?

A: A class defined inside another class. It is a member of the enclosing class.

Q: What is the scope resolution operator?

A: :: used to define methods outside class, access static members, or access global variables.

Q: What is the mutable keyword?

A: Allows a member variable to be modified even inside a const member function.

Q: What is a Copy Constructor?

A: ClassName(const ClassName &obj). Creates a new object as a copy of an existing one.

Memory & Pointers in C++

Q: malloc vs new return type?

A: malloc returns void*. new returns the exact object pointer type.

Q: free vs delete?

A: free releases memory. delete calls the destructor AND releases memory.

Q: What is delete[]?

A: Used to delete arrays allocated with new[]. Using delete (without []) on an array causes UB.

Q: What is std::unique_ptr?

A: A smart pointer with exclusive ownership. Cannot be copied, only moved.

Q: What is std::shared_ptr?

A: A smart pointer that allows multiple pointers to own the same resource (Ref-counting).

Q: What is std::make_shared?

A: A helper function that allocates memory for the object and the control block in one go (optimization).

Q: What is a circular dependency in smart pointers?

A: Two shared_ptrs pointing to each other, preventing the ref-count from reaching 0. Solved with weak_ptr.

Q: What is placement new?

A: Allows constructing an object in a pre-allocated memory buffer. new (address) ClassName();.

Q: What is a Reference?

A: An alias for an existing variable. Must be initialized upon declaration and cannot be null.

Q: Pointer vs Reference?

A: Pointers can be null/reassigned; references cannot. Pointers have their own address; references share the address.

Standard Template Library (STL)

Q: What is a Container?

A: An object that stores a collection of other objects (Vector, List, Map).

Q: What is an Iterator?

A: An object that points to an element in a container, allowing traversal (like a smart pointer).

Q: vector::size() vs vector::capacity()?

A: size is the number of elements. capacity is the allocated memory space before it needs to resize.

Q: What is vector::reserve()?

A: Requests that the vector capacity be at least enough to contain n elements (prevents reallocations).

Q: Time complexity of vector access?

A: O(1) - Constant time.

Q: Time complexity of list access?

A: O(n) - Linear time (must traverse).

Q: map vs set?

A: set stores unique keys. map stores unique Key-Value pairs.

Q: Internal structure of std::map?

A: Red-Black Tree (Self-balancing BST).

Q: Internal structure of std::unordered_map?

A: Hash Table.

Q: What is a Functor?

A: A class/struct that overloads the () operator, allowing objects to be used like functions.

Q: What is a Predicate?

A: A functor or function that returns a boolean (used in sort, find_if).

Q: What is std::sort complexity?

A: O(N log N) (Introsort: Mix of QuickSort, HeapSort, and InsertionSort).

Q: What is std::pair?

A: A struct holding two heterogeneous objects (first, second).

Q: What is std::array (C++11)?

A: A wrapper around static C-style arrays. It doesn't decay to a pointer automatically and knows its size.

Q: What is std::deque?

A: Double-ended queue. Elements can be added to front or back efficiently.

Modern C++ (11/14/17/20)

Q: What is nullptr?

A: A type-safe pointer literal representing a null pointer, replacing NULL macro.

Q: What is auto deduction?

A: Compiler infers type from initializer. auto x = 5; -> int.

Q: What is decltype?

A: Inspects the declared type of an entity or expression (e.g., decltype(x) y = x;).

Q: What is a Lambda capture list []?

A: Defines what outside variables are available inside the lambda. [=] (by value), [&] (by ref).

Q: What is std::move?

A: Casts an l-value to an r-value, enabling move semantics (transferring ownership instead of copying).

Q: What is a move constructor?

A: Class(Class&& other). It steals resources from other and nulls out other.

Q: What is constexpr?

A: Evaluated at compile time.

Q: What is std::tuple?

A: A generalization of std::pair holding a collection of heterogeneous elements.

Q: What is std::optional (C++17)?

A: A wrapper that may or may not contain a value, eliminating the need for magic numbers or null pointers.

Q: What is std::variant (C++17)?

A: A type-safe union. It can hold one of several specified types.

Q: What is std::any (C++17)?

A: A type-safe container for single values of any type.

Q: What is std::string_view (C++17)?

A: A lightweight, non-owning reference to a string. Avoids string copying.

Q: What are Concepts (C++20)?

A: A way to specify constraints on template arguments (e.g., template).

Q: What are Coroutines (C++20)?

A: Functions that can be suspended and resumed (using co_await, co_yield).

Q: What is if constexpr?

A: Compile-time if. The false branch is discarded during compilation (good for templates).

More Chapters