Prog Lang Interview
Prog Lang Interview
Here is a comprehensive list of frequently asked C programming interview questions that are often
posed to entry-level candidates for software developer roles. The questions focus on theoretical
aspects of the C language, ensuring depth of knowledge without expecting much practical
application.
Frequently Asked C Programming Interview Questions
1. What is C language?
C is a general-purpose, procedural programming language developed by Dennis Ritchie in 1972 at
Bell Labs. It is widely used for system and application software, embedded systems, and low-level
programming tasks due to its efficiency and control over hardware.
2. Why is C called a mid-level programming language?
C is called a mid-level programming language because it combines features of both high-level and
low-level languages. It allows for system-level programming (like assembly) and also provides
abstractions that make it easier to write applications (like high-level languages)[1][2].
3. What are the key features of the C language?
Some key features of C include:
Simple and efficient: Easy to learn and fast execution.
Mid-level language: Combines low-level hardware control with high-level abstractions.
Portable: Code written in C can be run on different machines with minimal or no modifications.
Structured programming: Supports functions and blocks, which help in organizing code.
Rich library support: Provides numerous built-in functions[4].
4. What is the difference between a local variable and a global variable?
Local variable: Declared inside a function or block and accessible only within that function or
block.
Global variable: Declared outside all functions and accessible throughout the entire
program[1].
5. What is a pointer in C?
A pointer is a variable that stores the memory address of another variable. It allows direct access to
memory and manipulation of data stored at specific addresses.
6. What is the difference between malloc() and calloc()?
malloc(): Allocates a single block of memory without initializing it.
https://md2pdf.netlify.app 1/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
calloc(): Allocates multiple blocks of memory and initializes all bits to zero[3].
7. What is the use of the static keyword in C?
The static keyword has three main uses:
For variables inside functions, it preserves their value between function calls.
For global variables, it restricts their scope to the file they are declared in.
For functions, it limits their visibility to the file they are declared in[3].
8. What are storage classes in C?
Storage classes define the scope (visibility) and lifetime of variables/functions within a C program.
The four storage classes are:
auto: Default for local variables.
register: Suggests storing variables in CPU registers.
static: Preserves variable value across function calls.
extern: Extends visibility across multiple files[4].
9. What are preprocessor directives in C?
Preprocessor directives are commands that give instructions to the compiler to preprocess the
information before actual compilation starts. Examples include #define , #include , #ifdef , etc.
10. What is typecasting in C?
Typecasting is the process of converting one data type into another. It can be done implicitly by the
compiler or explicitly by the programmer using casting operators like (int) , (float) , etc.[1].
11. What are arrays in C?
An array is a collection of elements of the same data type stored at contiguous memory locations.
Arrays allow you to store multiple values under a single name.
12. Explain recursion with an example in C.
Recursion occurs when a function calls itself directly or indirectly to solve a problem. Example:
int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}
https://md2pdf.netlify.app 2/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
Dynamic memory allocation allows you to allocate memory during runtime using functions like
malloc() or calloc() :
int *ptr = (int*) malloc(5 * sizeof(int)); // Allocates memory for an array of five in
Infinite loops are often used when waiting for external events like user input.
Here is a more advanced set of C programming interview questions, tailored for candidates with 2-
3 years of experience. These questions focus on deeper theoretical aspects, memory
management, and comparisons with other programming languages, as well as computer
architecture-related concepts.
Advanced C Programming Interview Questions
1. What is the difference between static and dynamic memory allocation in C?
Static Memory Allocation: Memory is allocated at compile-time. The size of variables is fixed,
and memory cannot be resized during program execution. It uses the stack.
Dynamic Memory Allocation: Memory is allocated at runtime using functions like malloc() ,
calloc() , or realloc() . It allows resizing of memory blocks and uses the heap[5][6].
2. What are the main issues associated with dynamic memory allocation?
https://md2pdf.netlify.app 4/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
Memory Leaks: If dynamically allocated memory is not freed using free() , it can lead to
memory leaks.
Fragmentation: Internal and external fragmentation can occur if memory is not efficiently
managed. External fragmentation happens when there are small free blocks that cannot be
utilized[9].
Performance Overhead: Dynamic allocation involves more overhead than static allocation due
to the need to manage the heap[5].
3. Explain the difference between malloc() and calloc() in terms of
memory allocation.
malloc() : Allocates a single block of memory without initializing it. The content of the
allocated block remains uninitialized.
calloc() : Allocates multiple blocks of memory and initializes all bytes to zero[1][6].
https://md2pdf.netlify.app 5/37
7. Explain how arrays are stored in memory in C.
16/11/2024, 11:01 md2pdf - Markdown to PDF
Arrays in C are stored in contiguous blocks of memory. The elements of an array are laid out
sequentially in increasing order of their index, with each element occupying space equal to its data
type.
8. What is the difference between arrays in C and arrays in higher-level
languages like Python or Java?
In C, arrays have a fixed size determined at compile-time or dynamically at runtime using
pointers. They do not support resizing after allocation.
In higher-level languages like Python or Java, arrays (or lists) can grow dynamically and offer
built-in methods for resizing and manipulation.
9. What is a volatile keyword in C? How does it affect optimization?
The volatile keyword tells the compiler that the value of a variable may change unexpectedly
(e.g., hardware registers). This prevents the compiler from optimizing code by caching variable
values, ensuring that every access fetches fresh data from memory.
10. How does C handle integer overflow?
C does not check for integer overflow by default. If an integer operation exceeds its maximum
value, it wraps around (modular arithmetic). For example, adding 1 to INT_MAX results in INT_MIN .
11. Explain how memory alignment works in C and why it’s important.
Memory alignment refers to arranging data in memory according to specific boundaries (e.g., 4-
byte boundaries for integers). Proper alignment ensures efficient access by the CPU, reducing
performance penalties associated with misaligned data access[9].
12. What is a union in C? How does it differ from a structure?
A union allows storing different data types in the same memory location but only one member can
hold a value at any time. A structure allocates separate memory for each member, allowing multiple
members to hold values simultaneously.
13. How do you prevent buffer overflows in C?
Buffer overflows can be prevented by:
Using bounds checking when accessing arrays.
Using safer alternatives like snprintf() instead of sprintf() .
Validating input lengths when reading from user input or files.
https://md2pdf.netlify.app 6/37
14. What is a double pointer (pointer to pointer) in C? Give an example use
16/11/2024, 11:01 md2pdf - Markdown to PDF
case.
A double pointer stores the address of another pointer. It’s commonly used for dynamic
multidimensional arrays or modifying pointers within functions.
Example:
void modifyPointer(int **ptr) {
*ptr = malloc(sizeof(int));
}
15. How does dynamic memory allocation differ between C and languages like
Java or Python?
In C:
Memory management is manual using malloc() , calloc() , and free() . In Java/Python:
Memory management is automatic via garbage collection, which periodically deallocates
unused objects without explicit programmer intervention[7].
16. What are near, far, and huge pointers? Why are they obsolete today?
These pointers were used in older architectures (like DOS) to manage segmented memory models:
Near pointers: Pointed within a single segment (64KB).
Far/huge pointers: Could point across segments. They are obsolete today because modern
systems use flat memory models where all addresses are linear[10].
17. Explain how virtual memory works at a high level and its relevance to C
programming.
Virtual memory allows programs to use more memory than physically available by swapping pages
between RAM and disk storage. In C programming, this affects how large data structures like arrays
behave when they exceed physical RAM limits.
18. What happens if you try to free already freed memory?
Freeing already freed memory results in undefined behavior, which may cause crashes or
corruption of heap structures managed by the operating system.
19. How does paging work in operating systems concerning dynamic memory
allocation?
https://md2pdf.netlify.app 7/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
Paging divides virtual memory into fixed-size pages that map to physical frames in RAM. When
dynamically allocating large amounts of memory ( malloc() ), pages may be swapped between
disk and RAM as needed based on access patterns.
20. Why might you choose C over languages like Python for system-level
programming tasks?
C provides low-level control over hardware resources (e.g., direct access to memory via pointers),
which makes it ideal for system-level programming tasks like writing operating systems or
embedded software where performance and resource control are critical[7].
Here is a comprehensive list of 30 C++ interview questions, ranging from intermediate to advanced
levels, designed for candidates with a strong background in C++ and computer science
fundamentals. The questions focus on core C++ concepts, memory management, object-oriented
programming (OOP), and deeper computer architecture-related topics.
Intermediate to Advanced C++ Interview Questions
1. What is the difference between C and C++?
C is a procedural programming language, while C++ supports both procedural and object-oriented
paradigms. C++ introduces classes, objects, inheritance, polymorphism, encapsulation, and
abstraction. Additionally, C++ offers features like function overloading, operator overloading, and
templates that are not present in C.
2. Explain the concept of Object-Oriented Programming (OOP) in C++.
OOP in C++ is based on four key principles:
Encapsulation: Bundling data and methods that operate on that data.
Abstraction: Hiding implementation details and exposing only essential features.
Inheritance: Deriving new classes from existing ones to promote code reuse.
Polymorphism: Allowing functions or operators to behave differently based on the context
(e.g., function overloading and virtual functions).
3. What are access specifiers in C++?
Access specifiers define the access level of class members:
Public: Members are accessible from outside the class.
Private: Members are accessible only within the class.
Protected: Members are accessible within the class and derived classes.
https://md2pdf.netlify.app 8/37
4. What is the difference between a reference and a pointer in C++?
16/11/2024, 11:01 md2pdf - Markdown to PDF
Reference: Must be initialized when declared, cannot be null, and cannot be reassigned.
Pointer: Can be initialized later, can be null or point to different objects during its lifetime.
5. What is the purpose of the virtual keyword in C++?
The virtual keyword is used to enable runtime polymorphism by allowing derived classes to
override base class methods. When a method is declared as virtual in a base class, the derived
class can provide its own implementation.
6. What is a pure virtual function?
A pure virtual function is a function that has no implementation in the base class and must be
overridden by derived classes. It is declared using = 0 syntax:
class Base {
virtual void display() = 0; // Pure virtual function
};
Operator overloading allows customizing the behavior of operators for user-defined types (e.g.,
classes). For example, you can overload the + operator for a Complex number class:
Complex operator+(const Complex& c1, const Complex& c2);
11. What is multiple inheritance in C++, and when would you use it?
Multiple inheritance allows a derived class to inherit from more than one base class. It can be useful
when combining functionalities from different classes but should be used carefully to avoid
ambiguity issues (e.g., diamond problem).
12. What is the diamond problem in multiple inheritance? How does C++
resolve it?
The diamond problem occurs when two base classes inherit from the same ancestor class, and a
derived class inherits from both base classes. This leads to ambiguity about which ancestor's
members should be inherited. It is resolved using virtual inheritance, which ensures only one copy
of the common base class exists.
class A {};
class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {}; // D has only one copy of A
Dynamic arrays can be created using pointers with new[] . Memory must be explicitly deallocated
using delete[] . Failure to do so leads to memory leaks.
int* arr = new int[10]; // Allocate array
delete[] arr; // Deallocate array
17. What are namespaces in C++, and why are they important?
Namespaces prevent name collisions by grouping related entities under a unique name:
namespace MyNamespace {
int x;
}
20. What is STL (Standard Template Library)? What are its components?
STL provides generic data structures and algorithms:
Containers (e.g., vector, list)
Iterators (to traverse containers)
https://md2pdf.netlify.app 11/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
This technique is useful for custom memory management scenarios where precise control over
memory allocation is required.
https://md2pdf.netlify.app 12/37
26. How does thread safety relate to static variables inside functions in
16/11/2024, 11:01 md2pdf - Markdown to PDF
multithreaded environments?
Static variables inside functions retain their value across invocations but can lead to race
conditions if accessed by multiple threads simultaneously without proper synchronization
mechanisms like mutexes or atomic operations.
27. Compare lock-based synchronization with lock-free programming
techniques like atomic operations or compare-and-swap (CAS).
Lock-based synchronization uses mutexes or semaphores but can lead to contention or deadlocks
if not used carefully. Lock-free programming uses atomic operations like CAS
( compare_exchange_strong ) to avoid locks but requires careful design to prevent race conditions
while ensuring correctness.
28. How does paging work at the OS level when dynamically allocating large
amounts of memory using new or malloc() ?
Paging divides physical memory into fixed-size pages mapped into virtual address space via page
tables maintained by the OS kernel. When dynamically allocating large blocks of memory, pages
may need to be swapped between disk storage and RAM depending on available physical memory.
29. How do modern compilers optimize tail recursion calls in recursive
functions?
Modern compilers optimize tail-recursive functions by reusing stack frames for successive
recursive calls instead of pushing new frames onto the stack—this optimization prevents stack
overflow for deep recursions.
30. Explain how CPU branch prediction affects performance when using
conditional statements inside loops (e.g., if-statements).
Branch prediction attempts to guess which way a branch will go before it’s known definitively at
runtime; if predicted correctly, execution proceeds smoothly; if predicted incorrectly (branch
misprediction), there’s performance penalty due to pipeline flushing and re-fetching instructions.
Here is a collection of 30 Python interview questions designed for someone with around one year
of experience. These questions cover core Python concepts, object-oriented programming (OOP),
and some intermediate-level topics that are frequently asked in interviews. The questions are
designed to test your understanding of Python's syntax, features, and OOP principles.
Frequently Asked Python Interview Questions
https://md2pdf.netlify.app 13/37
1. What are the key features of Python?
16/11/2024, 11:01 md2pdf - Markdown to PDF
Python is:
Interpreted: Code is executed line by line.
Dynamically typed: Variable types are determined at runtime.
High-level: It abstracts away most low-level details like memory management.
Object-oriented: Supports OOP principles like inheritance, encapsulation, and polymorphism.
Extensive libraries: Python has a vast standard library and third-party modules.
2. What is the difference between lists and tuples in Python?
Lists: Mutable, meaning their elements can be changed after creation. Defined using square
brackets [] .
Tuples: Immutable, meaning their elements cannot be changed once created. Defined using
parentheses () .
3. How do you handle exceptions in Python?
Exceptions in Python are handled using try , except , else , and finally blocks:
try:
# Code that may raise an exception
except SomeException:
# Handle the exception
else:
# Code that runs if no exception occurs
finally:
# Code that always runs (cleanup)
class Child(Parent):
pass
c = Child()
c.greet() # Inherits greet() from Parent
@decorator
def say_hello():
print("Hello!")
say_hello()
12. What is the difference between a class method and a static method?
Class method ( @classmethod ): Takes cls as its first argument and can modify class state.
Static method ( @staticmethod ): Does not take self or cls as arguments; it behaves like a
regular function but belongs to the class’s namespace.
13. How does garbage collection work in Python?
Python uses automatic garbage collection to free memory by removing objects that are no longer
referenced by any variable. It uses reference counting and cyclic garbage collection to manage
memory.
14. What is PEP8, and why is it important?
PEP8 is the style guide for writing clean and readable Python code. It covers naming conventions,
indentation rules, line length limits, etc., to ensure consistency across projects.
15. What are generators in Python? How do they differ from regular functions?
Generators allow you to iterate over data lazily (one item at a time) using the yield keyword
instead of returning all results at once.
def my_generator():
yield 1
yield 2
gen = my_generator()
print(next(gen)) # Output: 1
print(next(gen)) # Output: 2
https://md2pdf.netlify.app 16/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
class A:
def greet(self):
print("Hello from A")
class B:
def greet(self):
print("Hello from B")
c = C()
c.greet() # Resolves using Method Resolution Order (MRO)
You can create custom context managers using the __enter__() and __exit__() methods.
20. Explain duck typing in Python with an example.
Duck typing refers to dynamic typing where an object's behavior determines its suitability for use
rather than its type.
class Duck:
def quack(self):
print("Quack!")
class Dog:
def quack(self):
print("Woof!")
https://md2pdf.netlify.app 17/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
def make_it_quack(animal):
animal.quack()
class Dog:
def speak(self):
return "Woof"
22. What is method overriding in Python? How does it differ from method
overloading?
Method overriding occurs when a child class provides its own implementation of a method
inherited from a parent class.
Unlike other languages like Java or C++, Python does not support traditional method
overloading based on argument types or counts; instead, default arguments or variable-length
arguments ( *args , **kwargs ) are used.
23. Explain how encapsulation works in Python with an example.
Encapsulation restricts access to certain attributes/methods by marking them as private using
underscores ( _ or __ ).
class MyClass:
def __init__(self):
self._protected_var = "Protected"
self.__private_var = "Private"
https://md2pdf.netlify.app 18/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
obj = MyClass()
print(obj._protected_var) # Accessible but discouraged conventionally
# print(obj.__private_var) # Raises AttributeError due to name mangling
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Bark"
25. Explain how inheritance affects method resolution order (MRO) in multiple
inheritance scenarios.
Python uses C3 linearization (MRO) to determine the order in which base classes should be
searched when looking up methods or attributes during multiple inheritance.
You can view MRO using:
print(ClassName.__mro__)
https://md2pdf.netlify.app 19/37
27. How do you handle memory management issues such as memory leaks in
16/11/2024, 11:01 md2pdf - Markdown to PDF
Python?
Memory management issues can be handled by:
Using weak references ( weakref ) for large objects that should not prevent garbage collection.
Avoiding circular references by explicitly breaking them or using weak references.
28. How would you implement a singleton pattern in Python?
A singleton ensures only one instance of a class exists throughout the program's lifetime.
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance
29. How would you handle large datasets efficiently with limited memory
resources in Python?
To handle large datasets efficiently:
Use generators instead of loading all data into memory at once.
Process data chunks iteratively (e.g., reading files line by line).
Example using generators:
def read_large_file(file_name):
with open(file_name) as file:
for line in file:
yield line.strip()
30. Explain how multithreading works in Python given the Global Interpreter
Lock (GIL). When would you use multiprocessing instead?
The GIL prevents multiple native threads from executing simultaneously within one process due to
thread safety concerns with CPython's memory management.
For CPU-bound tasks requiring parallel execution, it's better to use multiprocessing rather than
multithreading since each process gets its own interpreter instance without GIL restrictions.
https://md2pdf.netlify.app 20/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
Here are 10 comparison-based problems that explore key differences and similarities between C,
C++, and Python. These problems cover various aspects of the languages, including memory
management, object-oriented programming, syntax, performance, and more. Each problem is
followed by a solution that explains how each language handles the particular concept.
int main() {
int *arr = (int*) malloc(5 * sizeof(int)); // Allocate memory for 5 integers
for (int i = 0; i < 5; i++) {
arr[i] = i + 1;
}
free(arr); // Free allocated memory
return 0;
}
C++: In C++, you can use new and delete for dynamic memory allocation. Alternatively,
smart pointers can be used for automatic memory management.
#include <iostream>
int main() {
int *arr = new int[5]; // Allocate memory for 5 integers
for (int i = 0; i < 5; i++) {
arr[i] = i + 1;
}
delete[] arr; // Free allocated memory
return 0;
}
Python: Python uses automatic garbage collection, so you don’t need to manually allocate or
free memory. Lists are dynamically managed by the interpreter.
https://md2pdf.netlify.app 21/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
class Person {
public:
string name;
int age;
void greet() {
cout << "Hello, my name is " << name << " and I am " << age << " years old." <
}
};
int main() {
Person p("Alice", 30);
p.greet();
}
Python: Python has a simpler syntax for defining classes but supports OOP principles like
inheritance and polymorphism.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
https://md2pdf.netlify.app 22/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
p = Person("Alice", 30)
p.greet()
C: C does not have built-in support for OOP. However, you can simulate OOP using structs and
function pointers.
#include <stdio.h>
#include <string.h>
typedef struct {
char name[50];
int age;
} Person;
int main() {
Person p;
strcpy(p.name, "Alice");
p.age = 30;
greet(&p);
}
3. Exception Handling
Problem:
Write code to handle division by zero in C, C++, and Python using exception handling mechanisms
available in each language.
Solution:
C: C does not have built-in exception handling like C++ or Python. Errors must be handled
manually using return codes or flags.
#include <stdio.h>
https://md2pdf.netlify.app 23/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
int main() {
int result = divide(10, 0);
}
C++: C++ provides exception handling using try , catch , and throw .
#include <iostream>
using namespace std;
int main() {
try {
cout << divide(10, 0) << endl;
} catch (const runtime_error& e) {
cout << e.what() << endl;
}
}
print(divide(10, 0))
4. Function Overloading
Problem:
Write overloaded functions to add two integers or two floats in C++, Python, and compare this with
how function overloading is handled in C.
Solution:
C++: Supports function overloading based on argument types or numbers.
#include <iostream>
using namespace std;
https://md2pdf.netlify.app 24/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
float add(float a, float b) { return a + b; }
int main() {
cout << add(2, 3) << endl; // Calls int version
cout << add(2.5f, 3.5f) << endl; // Calls float version
}
Python: Python does not support traditional function overloading. Instead, you can use default
arguments or variable-length arguments ( *args ).
def add(a, b):
return a + b
C: Function overloading is not supported in C. You would need to use different function names
or manually check types at runtime.
#include <stdio.h>
int main() {
printf("%d\n", add_int(2, 3));
printf("%f\n", add_float(2.5f, 3.5f));
}
5. File Handling
Problem:
Write code to open a file and read its contents in C, C++, and Python.
Solution:
C:
#include <stdio.h>
int main() {
FILE *file = fopen("test.txt", "r");
if (file == NULL) {
printf("Error opening file\n");
return -1;
https://md2pdf.netlify.app 25/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
}
char line[100];
fclose(file);
}
C++:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream file("test.txt");
if (!file.is_open()) {
cout << "Error opening file" << endl;
return -1;
}
string line;
file.close();
}
Python:
with open('test.txt', 'r') as file:
for line in file:
print(line.strip())
6. Multithreading
Problem:
Compare how multithreading is handled in C (POSIX threads), C++ (std::thread), and Python
( threading module). Write code to create two threads that print numbers from different ranges.
Solution:
https://md2pdf.netlify.app 26/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
C (POSIX threads):
#include <pthread.h>
#include <stdio.h>
int main() {
pthread_t t1, t2;
int start1 = 1;
int start2 = 6;
pthread_join(t1,NULL);
pthread_join(t2,NULL);
return 0;
}
C++ ( std::thread ):
#include <iostream>
#include <thread>
int main() {
std::thread t1(print_numbers, 1);
std::thread t2(print_numbers, 6);
t1.join();
t2.join();
}
https://md2pdf.netlify.app 27/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
def print_numbers(start):
for i in range(start,start+5):
print(i,end=' ')
t1 = threading.Thread(target=print_numbers,args=(1,))
t2 = threading.Thread(target=print_numbers,args=(6,))
t1.start()
t2.start()
t1.join()
t2.join()
template<typename T>
T add(T a,T b){
return a+b;
}
int main(){
cout<<add<int>(3 ,4)<<endl; // Works with integers.
cout<<add<float>(3.5 ,4.7)<<endl;// Works with floats.
}
https://md2pdf.netlify.app 28/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
In C we typically use macros or void pointers to achieve generic programming but it's not as flexible
as templates in C++ or dynamic typing in Python.
8. Variable Scope
Problem:
Compare how variable scope works in functions across these three languages when variables are
declared inside functions vs global variables.
Solution:
In all three languages:
Variables declared inside functions are local to that function.
Global variables can be accessed from any part of the program unless shadowed by local
variables.
Example global variable usage:
C/C++ Global Variables Example
In both languages global variables can be declared outside any function scope.
#include<stdio.h>
//Global Variable
int x=10;
void func(){
x+=10;//Accessing global variable
printf("%d",x);
}
void main(){
func();
printf("%d",x);
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int n = 1000000;
int *arr = (int*)malloc(n * sizeof(int));
free(arr);
}
C++: In C++, you can use the std::sort() function from the <algorithm> header.
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
int main() {
int n = 1000000;
std::vector<int> arr(n);
std::cout << "Time taken in C++: " << (double)(end - start) / CLOCKS_PER_SEC << "
}
https://md2pdf.netlify.app 30/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
Python: In Python, you can use the built-in sorted() function or the sort() method for lists.
import random
import time
start = time.time()
arr.sort()
end = time.time()
#include <stdio.h>
#include <stdlib.h>
int main() {
int stack_var = 10; // Allocated on stack
int *heap_var = (int *)malloc(sizeof(int)); // Allocated on heap
*heap_var = 20;
C++: Similar to C, local variables are stored on the stack while dynamic memory allocation
using new is done on the heap.
#include <iostream>
int main() {
int stack_var = 10; // Stack allocation
int *heap_var = new int(20); // Heap allocation
Python: Python abstracts away memory management. Variables are automatically managed by
Python’s garbage collector. However, all objects in Python are allocated on the heap.
stack_var = 10 # This is technically stored on the heap
heap_var = [20] # Lists are dynamically allocated on the heap
int main() {
char str[] = "Hello World";
reverse(str);
printf("%s\n", str);
}
C++:
#include <iostream>
#include <algorithm>
https://md2pdf.netlify.app 32/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
using namespace std;
int main() {
string str = "Hello World";
reverse(str.begin(), str.end());
cout << str << endl;
}
Python:
str = "Hello World"
print(str[::-1]) # Slicing method to reverse string in Python
int main() {
char name[50];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
printf("Hello, %s", name);
}
C++:
#include <iostream>
using namespace std;
int main() {
string name;
cout << "Enter your name: ";
getline(cin, name);
cout << "Hello, " << name << endl;
}
Python:
https://md2pdf.netlify.app 33/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
int total = 0;
for (int i = 0; i < count; i++) {
total += va_arg(args, int);
}
va_end(args);
return total;
}
int main() {
printf("%d\n", sum(3, 1, 2, 3));
}
template<typename... Args>
int sum(Args... args) {
return (args + ...); // Fold expression (C++17)
}
int main() {
cout << sum(1, 2, 3) << endl;
}
https://md2pdf.netlify.app 34/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
Python ( *args ):
def sum(*args):
return sum(args)
print(sum(1, 2, 3))
int factorial(int n) {
if (n == 0)
return 1;
return n * factorial(n - 1);
}
int main() {
printf("%d\n", factorial(5));
}
C++:
#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 0)
return 1;
return n * factorial(n - 1);
}
int main() {
cout << factorial(5) << endl;
}
Python:
https://md2pdf.netlify.app 35/37
16/11/2024, 11:01 md2pdf - Markdown to PDF
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5))
int main(){
auto add=[](int x,int y){return x+y;};
cout<<add(2 ,3)<<endl;
}
C Anonymous Functions:
C does not have built-in support for lambda or anonymous functions like Python or C++. You
would need to use function pointers or macros to achieve similar behavior.
C/C++: Manual memory management using malloc/free or new/delete . This can lead to
issues like memory leaks or buffer overflows if not handled carefully.
Python: Automatic garbage collection manages memory safely without manual intervention.
18. Speed/Performance
Generally:
C/C++: Faster due to direct compilation into machine code and low-level control over
memory.
Python: Slower compared to C/C++ due to its interpreted nature and dynamic typing but
can be optimized using libraries like NumPy or through integration with C/C++ code.
19. Type Systems
C/C++: Statically typed languages where types must be declared explicitly.
Python: Dynamically typed language where types are inferred at runtime.
20. Standard Libraries
C/C++: Both have extensive standard libraries but require more manual work for common tasks
like file handling or networking.
Python: Comes with a rich standard library that simplifies many tasks such as file handling
( os , io ), networking ( socket , requests ), etc., making it more suitable for rapid
development.
https://md2pdf.netlify.app 37/37