Programming Basics Flashcards Preview

C++ Programming > Programming Basics > Flashcards

Flashcards in Programming Basics Deck (135)
Loading flashcards...
1
Q

Are references implemented as pointers?

A

References are generally implemented using pointers.

2
Q

What is a lock_guard?

What is the syntax to use a lock_guard?

A

lock_guard is a mutex wrapper which implements a convenient mechanism for owning a mutex for the duratio of the scoped block.

The syntax is:

std::lock_guard lock(g_i_mutex);

3
Q

Can multiple threads exist within the same process?

A

Yes

4
Q

When does a lock_guard try to lock a mutex?

When does a mutex locked by a lock_guard get released?

A

The lock_guard tries to lock the mutex as soon as it is created and unlocks it when it goes out of scope, automatically.

5
Q

What is a template?

A

Templates are special operators that specify that a class or a function is written for one or several generic types that are not yet known.

6
Q

How much memory does a pointer occupy?

A

32/64 bits depending on the system

7
Q

What’s the C library for threads?

A

p_threads

8
Q

How do I allocate a pointer to a constant variable?

A

const int * ptr;

9
Q

What is the difference in scope between a static and a global variable?

A

Static variables can be accessed only within their scope, while global variables are visible everywhere

10
Q

How do I define a template function?

A

template T max( T a, T b)
{
return( a > b ? a : b );
}

int max_int = max( 2.2, 2.5 ) ;

float max_float = max( 2.2, 2.5 )

11
Q

What is the difference between a mutex and a semaphore?

A

A mutex provides mutual exclusion, either producer or consumer can have the key (mutex) and proceed with their work.

A semaphore is a generalized mutex. In lieu of single buffer, we can split the 4 KB buffer into four 1 KB buffers (identical resources). A semaphore can be associated with these four buffers. The consumer and producer can work on different buffers at the same time.

12
Q

How do I define a template class?

A

template < class T >
class Foo {
private:
T _value;

public:
    Foo( T value ) : _value(value) { };
}
----------------------------
int main( int argc, char **argv )
{
    Foo < int > foo_int;
    Foo < float > foo_float;
}
13
Q

If a class has a static member and I create multiple instances of such class, do these object have each their own copy of the static variable or do they share the same one?

A

There can not be multiple copies of same static variables for different objects.

Therefore, multiple objects of the same class will share the same static members.

14
Q

How can I initialize a multidimensional array?

A

int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}

// Or even better:
int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};
15
Q

1) What is an array?
2) Are elements in an array contiguous in memory?
3) Are elements of an array of the same size?

A

1) An array is a sequence of elements of the same kind.
2) The elements of an array are contiguous in memory.
3) The elements of an array have all the same size.

16
Q

Difference between static and dynamically allocated arrays

A

Static array are allocated at compile time, therefore the size is pre-determined. Dynamically allocated arrays are allocated at runtime in the heap with the new operator, and their size is defined at runtime.

17
Q

Can static methods access non-static parts of the class?

A

No, they can only access static members and methods.

18
Q

What’s the difference between char str[4] and char* str?

A

The first is an array of char and as such is stored in the stack.

The second is a pointer to char and can be either:
- in the shared segment (read-only) if char *str = “GfG”;

  • in the heap if char str;
    int size = 4; /
    one extra for ‘\0’*/
    str = (char )malloc(sizeof(char)size);
19
Q

How can I expand the size of a string using pointers in C?

A

You need to allocate a new memory area

20
Q

Can I declare a static method in a class?

A

Yes, static methods can only access the static part of the class (members and methods).

21
Q

What is a unique pointer?

A

A unique_ptr is a container for a raw pointer, which the unique_ptr is said to own. A unique_ptr explicitly prevents copying of its contained pointer (as would happen with normal assignment), but the std::move function can be used to transfer ownership of the contained pointer to another unique_ptr.

22
Q

Is an exception an object?

A

Yes

23
Q

Does each call of a recursive function allocate a new stack frame?

A

Yes, therefore local variables are redefined and allocated.

24
Q

Memory allocation, deallocation and reallocation in C

A
  • malloc(): to allocate memory. Example: int* ptr = (int) mallow(10sizeof(int));
  • calloc(): allows contiguous allocation of memory. Example: ptr = (cast-type*)calloc(n, element-size);
  • free(): to de-allocate memory. Example: free(ptr)
  • realloc(): to dynamically change the memory allocation of a previously allocated memory (e.g., to increase size). Example: ptr = realloc(ptr, new_size);
25
Q

Can I define a pointer to a struct?

A

Yes, of course.

struct movies_t {
string title;
int year;
};

movies_t amovie;
movies_t * pmovie;

26
Q

What does it mean throwing an exception?

A

Throwing an exception means creating a new exception object containing information about the error, and providing it to the function that called the code where the error happened.

27
Q

What operator should I use to access a member of a reference to a class?

A

If you have a reference to an object, can use the standard dot operator class.method

28
Q

What is an automatic variable? Where is it stored?

A

auto is a modifier which specifies an “automatic” variable that is automatically created when in scope and destroyed when out of scope.

29
Q

What is the time complexity for accessing an element of an array?

A

O(1)

30
Q

Can I define a reference without initializing it?

A

No

31
Q

Casting in C++

A
  • const_cast: adds/remove const from a variable
  • static_cast: done at compile time, does things like conversion between types
  • dynamic_cast: can be used only with pointers and references to objects to convert between relative classes (e.g., from derived to base class)
  • reinterpret_cast: It is used to convert one pointer of another pointer of any type
32
Q

How do I allocate a constant pointer to a variable?

A

int *const ptr;

33
Q

What is the asterisk operator? What is the ampersand operator?

A

Asterisk: unary operator that applied to a pointer, returns the content of the pointed variable

Ampersand: unary operator that returns the address where a variable is stored.

34
Q

How do I access the members of a struct?

A

Dot operator if you have the struct itself of a reference to it, arrow operator if you have a pointer to the struct.

35
Q

Does a reference occupy memory?

A

No

36
Q

When should I use call by value and when call by reference?

A

If you want to change the object passed, call by reference or use a pointer; e.g., void f(type& x); or void f(type* x);.
If you don’t want to change the object passed and it is big, call by const reference; e.g., void f(const type& x);.
Otherwise, call by value; e.g. void f(type x);.

37
Q

1) What is a multidimensional array?

2) How can a multidimensional array be stored in memory?

A

Multidimensional arrays are 2D arrays, for example to memorize matrices (but in general are n-D).

In a 2D array, each element, we have an array of arrays: there is a first array, in which each element is an array itself.

Each element of the first array represents a row in the matrix. Each element in an element of the second array represents the column.

38
Q

What is a semaphore?
What is the syntax to create a semaphore?
What is the count of a semaphore?

A

A semaphore has a predefined maximum count, and a current count. You take ownership of a semaphore with a wait operation, also referred to as decrementing the semaphore. You release ownership with a signal operation, also referred to as incrementing the semaphore.

39
Q

What happens if I call n times a function in which a static variable is defined?

A

The static variable is allocated only the first time, any other time the function is called, the same memory is used (e.g., if a static variable is created and incremented in a function and this is called n times, the same variable is increased n times).

40
Q

What is the time complexity for adding an element in an array?

A
  • Linear time at the beginning and in the middle

- Constant time at the end

41
Q

What is an extern variable? Where is it stored?

A

extern is used when a file needs to access a variable in another file that it may not have #included directly. It is stored anywhere the actual variable is stored when created.

42
Q

How can I wait for a thread to finish before continuing?

A

Using the join function.

43
Q

If a class is static and goes out of scope, is its destructor invoked? When is it invoked?

A

Nope, it stays in memory and the destructor is invoked at the end of the main.

44
Q

Can a pointer be NULL? Can a reference be NULL?

A

A pointer can be NULL. A reference cannot be NULL.

45
Q

What is a shared pointer?

A

A shared_ptr is a container for a raw pointer. It maintains reference counting ownership of its contained pointer in cooperation with all copies of the shared_ptr. An object referenced by the contained raw pointer will be destroyed when and only when all copies of the shared_ptr have been destroyed.

46
Q

Can I declare a static class object? How?

A

Just like variables, objects also when declared as static have a scope till the lifetime of program.

47
Q
  • What is a mutex?
  • How do I create a mutex?
  • What does it mean that a thread own a mutex?
A

The mutex class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads.

  • std::mutex mtx;
  • A thread owns a mutex when it locks it, meaning that it is the only one having access to it.
48
Q

Are the global variables defined in a process available to its threads?

A

Yes, since threads share the data segment.

49
Q

What is a pointer? How do I define a pointer?

A

A pointer is a variable that holds memory address of another variable.

int* ptr;

50
Q

What is recursion? How can I implement recursion?

A

Recursion tries to decompose a bigger problem into smaller sub-problems. The result of these sub-problems compose the solution to the original problem.

A function is said to be recursive if it calls itself.

A recursive function can only solve directly the so-called base case. If it is asked to solve a non-base case, it has to call itself with simplified input. At each call, the input data are simplified until a base case is found. Once this is found, the calls are closed, computing intermediate results.

51
Q

How can I handle strings in C++?

A

C++ has in its definition a way to represent sequence of characters as an object of class. This class is called std:: string. String class stores the characters as a sequence of bytes with a functionality of allowing access to single byte character.

52
Q

How do I allocate a constant pointer to a constant variable?

A

const int *const ptr;

53
Q

Where is a standard static array allocated?

A

It depends, can be in the stack frame or the data segment (if static).

54
Q

What’s the lifetime of a static variable?

A

Entire program.

55
Q

Can I re-assign a pointer? Can I re-assign a reference?

A

A pointer can be reassigned to point to a new memory location. A reference cannot be reassigned.

56
Q

What is a smart pointer?

A

Smart pointers prevent most situations of memory leaks by making the memory deallocation automatic. More generally, they make object destruction automatic: an object controlled by a smart pointer is automatically destroyed (finalized and then deallocated) when the last (or only) owner of an object is destroyed, for example because the owner is a local variable, and execution leaves the variable’s scope.

57
Q

What is a namespace? How do I define a namespace?

A

Namespaces address the problem of naming conflicts between different pieces of code. For example, you might be writing some code that has a function called foo(). One day, you decide to start using a third-party library, which also has a foo() function. The compiler has no way of knowing which version of foo() you are referring to within your code.

58
Q

Can I change the size of a char []?

A

No, you need to reallocate a larger array

59
Q

How many threads can own a semaphore?

A

As many as the max_count of the semaphore allows.

60
Q

What is a thread?

What’s the difference between a thread and a process?

A

A thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system.

61
Q

Implicit/Explicit Casting in C

A
  • Implicit: done by the compiler, done whenever an expression of type T1 is used where an expression of type T2 is expected. Can lead to loss of information.
  • Explicity: done by the user with (new_type) var
62
Q

What is the time complexity of adding an element in a dynamic array?

A

Constant if the array is not full, linear if it is full, since it is necessary to copy over the elements from the previous array.

63
Q

What is a callable?

A

A callable is a portion of code which is executed by the thread.

64
Q

Can I create my own exception?

Can I derive from a base exception?

A

Yes to both.

65
Q

What is the difference between call by value and call by reference?

A

Call by value creates a copy of the variable passed. Call by reference instead provides a reference to the already allocated variable.

66
Q

What is tail recursion?

A

Tail recursion is a special kind of recursion where the recursive call is the very last thing in the function. It’s a function that does not do anything at all after recursing.

The advantage of tail recursion is that the stack allocated before the recursive call is not useful anymore (since the call does not do anything else), therefore the compiler can optimize the code and speed it up.

67
Q

Where is a dynamically allocated array allocated?

A

In the heap.

68
Q

What is a dangling pointer?

A

It is a pointer to a memory location which is not allocated (for example, was deleted).

69
Q

What’s the syntax to lock a mutex?

A

std: :mutex mtx;

mtx. lock();

70
Q

What happens if a thread tries to lock an already locked mutex?

A
  • If you use .lock(), the thread that locked it will get blocked until the mutex is released.
  • If you use .try_lock(), you well get a false as return value.
71
Q

What is a wait operation on a semaphore?

What is a signal operation on a semaphore?

A

Waiting on a semaphore means decrementing the counter of the samaphore. If the count was greater than zero then the decrement just happens, and the wait call returns. If the count was already zero then it cannot be decremented, so the wait call will block until another thread increases the count by signalling the semaphore.

Signaling means incrementing the counter of the samephore semaphore.

72
Q

What happens if I wait a semaphore but its counter is zero?
What happens if I wait a semaphore and its counter is non-zero?
What happens if I signal a semaphore and its counter is its max value?

A
  • The code is blocked until another thread signals.
  • The counter is decremented and the code executes.
  • Nothing, the counter cannot get larger than its max value.
73
Q

How do refer to a variable defined in a specific namespace?

A

To call the namespace-enabled version of foo():

mycode::foo(); // calls the “foo” function in the “mycode” namespace

74
Q

Where is the thread class defined in C++?

A

std::thread

75
Q

How do I define a reference?

A

int A = 5;

int& rA = A;

76
Q

Does an array provide random access?

A

Yes, thanks to the fact that the elements are equal size and contiguous

77
Q

What is a register variable? Where is it stored?

A

A register variable is similar to automatic variables, but are stored in the CPU register for faster access.

78
Q

Is the executable code of a process shared among its threads?

A

Yes, since threads share the code segment.

79
Q

Dynamic programming and memoization

A

Dynamic programming is a technique to solve one of the main issues with recursion, which is the recursive call to the same functions multiple times. Dynamic programming solves this issue through memoization: we create a data structure which stores the value of the intermediate calls in a way that it is easy to use to check whether we already computed the result for a given input.

80
Q

How can I access any element of an array?

A

Using the operator [idx]. It is possible to access any element with the same constant time since the elements have all the same size and are contiguous.

81
Q

Where is char *str = “GfG”; stored in memory?

A

In the shared segment as read-only

82
Q

How can I access the element i,j in a multidimensional array?

A

vec[i][j]

83
Q

What does detach do to a thread?

A

detatch() separates the thread of execution from the thread object, allowing execution to continue independently.

84
Q

How can I throw an exception?

A
try
{
    float *array = new float[-1];
}
catch( std::bad_alloc e )
{
    std::cerr << e.what() << std::endl;
}
85
Q

Is a character of array faster or slower than string?

A

Strings are slower when compared to implementation than character array.

86
Q

What are advantages of const over #define?

A

define is error prone as it is not enforced by the compiler like const is. It merely declares a substitution that the preprocessor will perform without any checks; that is const ensures the correct type is used, whereas #define does not.

87
Q

What does joining a thread mean?

A

Once a thread has started we may need to wait for the thread to finish before we can take some action. To wait for a thread use the std::thread::join() function.

88
Q

Can a thread signal a semaphore without having waited first?

A

Yes.

89
Q

What is the duration of a global variable? What is its scope?

A

Global variables have static duration, which means they are created when the program starts and are destroyed when it ends. Global variables have file scope.

90
Q

Are the dynamically allocated variables shared among threads?

A

Yes, since threads share the heap.

91
Q

How can I create multidimensional arrays?

A

int three_d[10][20][30];

92
Q

If I declare a new variable with the same name of a global one, is the global hidden? If so, how can I access then the global variable?

A

Yes, to access the global one should use the scope operator “::”.

93
Q

Until when does a static variable stay in the memory?

A

Until when the program ends.

94
Q

What is the difference between a mutex and a binary semaphore?

A

Strictly speaking, a mutex is locking mechanism used to synchronize access to a resource. Only one task (can be a thread or process based on OS abstraction) can acquire the mutex. It means there is ownership associated with mutex, and only the owner can release the lock (mutex).

Semaphore is signaling mechanism (“I am done, you can carry on” kind of signal). For example, if you are listening songs (assume it as one task) on your mobile and at the same time your friend calls you, an interrupt is triggered upon which an interrupt service routine (ISR) signals the call processing task to wakeup.

95
Q

How do I create my own exception?

A

include

class Exception : public std::runtime_error
{
public:
    Exception() : std::runtime_error("Exception") { };
};
96
Q

What is a struct? What is the syntax to define a struct?

A

A data structure (struct) is a group of data elements grouped together under one name. These data elements, known as members, can have different types and different lengths. Data structures can be declared in C++ using the following syntax:

struct type_name {
   member_type1 member_name1;
   member_type2 member_name2;
   member_type3 member_name3;
} object_names;
97
Q

Can I iterate over pointers?

A

Yes, for example using ++.

98
Q

What is a volatile variable? Where is it stored?

A

volatile is a special type of modifier which informs the compiler that the value of the variable may be changed by external entities other than the program itself.

99
Q

What’s the difference in terms of memory between chars array and string?

A

Size of the character array has to allocated statically, more memory cannot be allocated at run time if required. Unused allocated memory is wasted in case of character array.

In case of strings, memory is allocated dynamically. More memory can be allocated at run time on demand. As no memory is preallocated, no memory is wasted.

100
Q

What happens if a mutex is destroyed while still owned by a thread?
What happens if a thread terminates before releasing a mutex it owns?

A

The behavior of a program is undefined if a mutex is destroyed while still owned by any threads, or a thread terminates while owning a mutex.

101
Q

How can I define a string in C?

A

In C, a string can be referred either using a character pointer or as a character array.

102
Q

What is the time complexity for removing an element from an array?

A
  • Linear time at the beginning (elements must be moved) and in the middle
  • Constant time at the end (no move needed)
103
Q

How do I allocate an object with a specific type of a template class?

A

template < class T >
class Foo {
private:
T _value;

public:
    Foo( T value ) : _value(value) { };
}
----------------------------
int main( int argc, char **argv )
{
    Foo < int > foo_int;
    Foo < float > foo_float;
}
104
Q

Explain static and dynamic memory allocation with an example each.

A

When amount of memory to be allocated is known beforehand i.e. at the the time of compilation, it is known as Static Memory Allocation. Once the memory is allocated statically, it cannot be deallocated during program run. So it leads to wastage of storage space.
Example: int A[100];

When amount of memory to be allocated is not known beforehand, rather it is determined at the time of program run, it is called Dynamic Memory Allocation. It leads to efficient utilization of storage space.
Example:
cout &laquo_space;” Enter number of elements: “;
cin&raquo_space; N;
int *A = new int[N]; // dynamic memory allocation

105
Q

What is a reference?

A

A reference variable is an alias, that is, another name for an already existing variable

106
Q

What’s the input to the constructor of a thread object?

A

It needs a callable and (optional) a set of parameters

std::thread thread_object(fn_class_object(), params)

107
Q

What is a dynamic array?

A

Dynamic arrays are a solution to have arrays which can change in size. We can store the pointer to the array, its max capacity and its size (element actually filled). If the array is full, we allocate a new array of larger capacity, copy the elements over from the previous one, and move the pointer to the new array to use it.

108
Q

What operator should I use to access a member of a pointer to a class?

A

If you have a pointer to an object, should use the arrow operator “->”

109
Q

Can I provide params to a function called in a thread?

A

Yes, specifying them after the callable in the constructor.

110
Q

How do I start a thread?

What is the syntax to define a thread?

A
#include 
void foo(param) 
{ 
    // Do something 
} 
// The parameters to the function are put after the comma 
std::thread thread_obj(foo, params);
111
Q

What does const do?

A

The qualifier const can be applied to the declaration of any variable to specify that its value will not be changed

112
Q

What is a static variable? Where is a static variable stored in memory?

A

A static variable stays in the memory until the program ends. They are stored in the data segment.

113
Q

When should I use a pointer and when a reference?

A
  • Use references:
  • In function parameters and return types.

Use pointers:

  • Use pointers if pointer arithmetic or passing NULL-pointer is needed. For example for arrays (Note that array access is implemented using pointer arithmetic).
  • To implement data structures like linked list, tree, etc and their algorithms because to point different cell, we have to use the concept of pointers.
114
Q

What are the standard exceptions?

A
  • bad_alloc
  • bad_cast
  • bad_exception
  • bad_typeid
  • logic_error
  • runtime_error
115
Q

How do I use a namespace all over a file?

A

using namespace mycode;

116
Q

What does const do after the parameters of a function?

A

It does not allow the function to modify the members of the class it belongs to. This happens because the pointer this is not passed as input parameter to the function (whereas it usually happens).

117
Q
  • How does communication among threads happen?

- How is communication between threads and between processes different?

A

Communication between threads happens by memory sharing.

118
Q

Does each call of a recursive function have its own local variable?

A

Yes

119
Q

How can I allocate dynamically a string in the heap segment in C?

A

Allocating a pointer and initializing it with malloc

char* str;
str = (char*)malloc(n * sizeof(char))

120
Q

What’s the difference between lock() and try_lock()?

A

Lock is blocking, meaning that if it does not succeed, it blocks the execution of the code until the mutex is released. try_lock tries to lock it and, if it fails, it returns false.

121
Q

How do I call a template function on a specific type?

A
template 
T max( T a, T b)
{
    return( a > b ? a : b );
}

int max_int = max( 2.2, 2.5 ) ;

float max_float = max( 2.2, 2.5 )

122
Q

Memory allocation, deallocation and reallocation in C++

A
  • new: to allocate a new variable. Example: int* ptr = new int[4];
  • delete: to deallocate memory. Example: delete [] ptr;
123
Q

What is a template function?

A

It is a function whose parameters and return type are not known in advance, but can be defined by the user when using it.

124
Q

What is an exception?

How should runtime errors be handled in C++?

A

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system.

125
Q

What is concurrent programming?
What is a critical section?
What is a critical resource?

A

Concurrent programming deals with portions of code called critical sections which need to operate on the same data, called critical resources.

126
Q

What is the main difference between array of chars and std::string?

A

A character array is simply an array of characters can terminated by a null character. A string is a class which defines objects that be represented as stream of characters.

127
Q

List the main functions provided by std::string()

A
push_back() :- 
pop_back() :- 
capacity() :- 
resize() :- 
shrink_to_fit() :- 
begin() :- 
end() :- 
copy(“char array”, len, pos) :- 
clear(): 
append(): 
front()/back(): 
find(str):
128
Q

What is a jagged array?

A

A jagged array is an array having elements all of different sizes.

129
Q

What is a global variable? Where is it declared? Where is it stored?

A

Variables declared outside of a function are called global variables.

130
Q

Does a pointer occupy memory?

A

Yes, it occupies memory to store the address of the memory location it points to

131
Q

Is there any alternative do joining a thread?

A

If we don’t want to wait for a thread to finish, we can use the detach() function. detatch() separates the thread of execution from the thread object, allowing execution to continue independently. Any allocated resources will be freed once the thread exits.

132
Q

Fundamental data types: definition, size, possible modifiers

A
  • int: 4 bytes (signed, unsigned, long, short)
  • char: 1 byte (signed, unsigned)
  • bool: 1 bit
  • float: 4 bytes
  • double: 8 bytes
  • void: 0 bytes
  • wide_char: 2/4 bytes
133
Q

How do I modify the content of the cell a pointer points to?

A

int x = 10;
int* ptr = &x;
*ptr = 11;

134
Q

How can I unlock a mutex?

A

mutex_name.unlock();

135
Q

Do threads share memory?

A

Yes, they share

  • Data Segment(global variables,static data)
  • Address space.
  • Code Segment.
  • I/O, if file is open , all threads can read/write to it.
  • Process id of parent.
  • The Heap