vector<int> v(22);
bool b = (v[6]);
printf("%d", !b);
using namespace std;
typedef struct{
unsigned int age : 4;
unsigned char gender : 1;
unsigned int size : 2;
}child_t;
std::vector<int> v1{1,2,3},v2;
v2=v1;
v1.push_back(4);
v2.push_back(5);
union {
uint16_t a;
uint32_t b;
int8_t c;
} u1;
?:
new
::
.
std:: vector<int> *v1 = new std::vector<int>({1,2,3});
std:: vector<int> *v2;
v2=v1;
v1->push_back(4);
v2->push_back(5);
*v1:{1,2,3,4}; *v2:{5};
*v1:{1,2,3,4,5}; *v2:{1,2,3,4,5};
*v1:{1,2,3,4}; *v2:{1,2,3,5};
v1 and v2 point to the same vector.
Templates can be used with both classes and structs Refernce Reference
typedef struct {
int sunday:1;
int monday:1;
// more days
int friday:1;
int saturday:1;
} weekdays;
typedef char[7]: weekdays;
typedef struct {
bit sunday:1;
bit monday:1;
// more days
bit friday:1;
bit saturday:1;
} weekdays;
typedef struct {
bit sunday;
bit monday;
// more days
bit friday;
bit saturday;
} weekdays;
Reference NOTE: Correct syntax is that each variable size is 1 bit. bit
is not a type in C++.
auto x = 4000.22;
if(x)
y=a;
else
y=b;
y=a?b:x;
y=if(x?a:b);
y=(x&a)?a:(x&b)?b:0;
y=x?a:b;
#include <iostream>
int main(){
int x=10, y=20;
std::cout << "x = " << x++ << " and y = " << --y << std::endl;
std::cout << "x = " << x-- << " and y = " << ++y << std::endl;
return(0);
}
x = 10 and y = 20
x = 11 and y = 19
x = 11 and y = 19
x = 10 and y = 20
x = 10 and y = 19
x = 11 and y = 20
x = 11 and y = 20
x = 10 and y = 19
std::pair
that specifies the range (start and end) in which the variable will iterate.std::pair
that specifies the range (start and end) in which the elements will be accessed within the loop.int8_t a=200;
uint8_t b=100;
if(a>b)
std::cout<<"greater";
else
std::cout<<"less";
Note: a variant of the question below.
int8_t a=200;
uint8_t b=100;
std::cout<<"a="<<(int)a;
std::cout<<", b="<<(int)b;
Note: Implicit conversion from ‘int’ to ‘int8_t’ (aka ‘signed char’) changes value from 200 to -56
int x=5, y=2;
if(x & y) {
/*_part A_*/
}
else {
/*_part B_*/
}
get_length
function, which returns the length of a null-terminated string?int get_length(char *str) {
int count=0;
while(str[count++]);
return count-1;
}
int get_length(char *str) {
int count=0;
while(str!=NULL){
count++;
str++;
}
return count;
}
int get_length(char *str) {
int count=0;
while((*str)++)
count++;
return count;
}
int get_length(char *str) {
int count=0;
while(str++)
count++;
return count;
}
std::list
std::vector
std::priority_queue
std::map
int i = 0;
printf("%d", i++);
printf("%d", i--);
printf("%d", ++i);
printf("%d", --i);
ptr
?void *ptr;
int c=3; char d='A';
std::printf("c is %d and d is %c",c,d);
printf("1/2 = %f",(float)(1/2));
x
after executing this code?int x=10, a=-3;
x+=a;
ptr
, which has been set to point to a floating point variable g
. Which choice is a valid way to dereference ptr
to assign its pointed value to a float variable f
later in the program?float g;
void *ptr=&g;
float f=*(float)ptr;
float f=(float *)ptr;
float f=(float)*ptr;
float f=*(float *)ptr;
.*
operator and what does it do?(->)
, which allows you to access a member of an object through a pointer to the object.(.)
and the dereference operator (*)
, so it allows you to access the object that a member pointer points to.char buff[50] = "strings as arrays of characters are fun!"
char *str = buff+11;
char c;
c = buff[16];
c = str[5];
c = *(buff+16);
c = *(str+5);
c = *(buff[15]);
c = *(str[4]);
c = buff+15;
c = str+4;
c = buff[15];
c = str[4];
c = *(buff+15);
c = *(str+4);
c = *(buff[16]);
c = *(str[5]);
c = buff+16;
c = str+5;
class Animal{
//....
}
class Dog :: public Animal {
//....
};
class Dog : public Animal {
//....
};
public class Animal :: Dog {
//....
};
public class Dog extends Animal {
//....
};
#include <cstdio>
using namespace std;
int main(){
char c = 255;
if(c>10)
printf("c = %i, which is greater than 10", c);
else
printf("c = %i, which is less than 10", c);
return 0;
}
Technically, whether a char
is signed
or unsigned
is implementation-defined;
in the latter case, the second answer would be correct.
Reference
center
?coord center;
center.x = 5;
center.y = 3;
typedef struct coord {
int x;
int y;
};
typedef struct coord {
int x;
int y;
} coord;
typedef struct {
int x;
int y;
} coord;
struct coord {
int x;
int y;
};
typedef struct coord coord;
i
will not be used anywhere else in the code.for (i=1;i<10;i++){
cout<<i<<endl;
}
i=1;
while(i<10){
cout<<++i<<endl;
}
for (int i:{1,2,3,4,5,6,7,8,9}) {
cout<<i<<endl;
}
i = 1;
do {
cout<<i++<<endl;
} while(i<10);
i = 1;
loop:
cout<<i++<<endl;
if(i<10) goto loop;
#include "library.h"
#include
directive with those declarations and definitions.#include
directive by the entire contents of the source file library.h. This is similar to the Copy-Paste operation of library.h into main.cpp.is_even
, which takes in an integer and returns true if the argument is an even number and false otherwise. Which declarations are correct for overloaded versions of that function to support floating point numbers and string representations of numbers?bool is_even(int);
bool is_even(float f);
bool is_even(char *str);
bool is_even(float f);
bool is_even(char str);
bool is_even_float(float f);
bool is_even_str(char *str);
float is_even(float f);
char *is_even(char *str);
my_library.h
?#ifdef MY_LIBRARY_H
#define MY_LIBRARY_H
// my_library.h content
#endif /* MY_LIBRARY_H */
#ifndef MY_LIBRARY_H
#define MY_LIBRARY_H
// my_library.h content
#endif /* MY_LIBRARY_H */
#ifdef MY_LIBRARY_H
#undef MY_LIBRARY_H
// my_library.h content
#endif /* MY_LIBRARY_H */
#define MY_LIBRARY_H
#include MY_LIBRARY_H
// my_library.h content
#undef MY_LIBRARY_H
std::vector<std::vector<int>> thematrix;
std::vector
cannot contain more std::vector
containers as its elements.std::vector[std::vector[int]] thematrix;
>>
is parsed as the shift-right operator, and thus results in a compile error.sprite->x
sprite.x
sprite.*x
(*sprite).x
*sprite.x
complexNumber
. Which code will result in an equivalent object?complexNumber(float real, float im)
: real_part(real),
im_part(im){}
complexNumber(float real, float im) {
this->real = real_part;
this->im = im_part;
}
complexNumber(float real, float im) {
this->real_part(real);
this->im_part(im);
}
complexNumber(float real, float im) {
this->real_part = real;
this->im_part = im;
}
complexNumber(float real, float im) {
this->real_part = ℜ
this->im_part = &im;
}
bool x=true, y=false;
if (~x || y) {
/*part A*/
} else {
/*part B*/
}
(~x || y)
always results in true if y==false
.(~x || y)
is invalid, thus false.~x
is not zero, meaning true.~x
is false and y
is false, thus the OR
operation evaluates as false.int32_t nums[3]={2,4,3};
std::cout << ( nums[0] << nums[1] << nums[2] );
nums[0]
, nums[1]
, and nums[2]
, in that order, with no spaces.0
243
float values[5]={0.54f, 2.71828f, 3.14159f, 5.499999f, 10.0f};
for(auto f:values)
printf("%i ",(int)(f+0.5f));
0.54 2.71828 3.14159 5.499999 10.0
1 3 4 6 11
0 2 3 5 10
1 3 3 5 10
std::priority_queue
std::list
std::vector
std::map
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream file1("text1.txt", ios::binary);
ofstream file2("text2.txt", ios::binary);
file2 << file1.rdbuf();
}
count
of my_class as static? / Alt.: Which statement is true when declaring the member variable count
as static?class my_class {
public: static int count;
}
0.44
?my_object
as shown below?my_class *my_object = new my_class();
delete(my_object);
free(my_object);
count
member function for the object pointer called grades
?class my_array{
public:
int count();
}; // ... more members above
int main(){
my_array *grades = new my_array();
}; // ... more code above
grades.count();
my_array->count();
grades->count();
my_array.count();
int i0=4, i1=6, i2=8;
int& nums[3]={i2,i0,i1};
std::cout<<nums[0]<<nums[1]<<nums[2];
nums
is an array of references, which is illegal.i2
, i0
, and i1
, in that order, with no spaces.child_t
?typedef struct{
unsigned int age : 4;
unsigned char gender : 1;
char : 0;
unsigned int size : 2;
}child_t;
child_t
is a type defined as a structure with bit fields. It has 4 bits for age and 1 bit for gender in the first byte, and 2 bits for size in the second byte.A->B
*(A.B)
B=A
(*A).B
&A.B
Note: a simpler variant of the question below.
A->B->C->D
A.B.C.D
*A.*B.*C.*D
&A.&B.&C.&D
*(*((*A).B).C).D
Note: a more complex variant of the question above.
auto buff = new char[50];
std::memset(buff,20,50);
CustomData
. Which choice is a correct declaration syntax to overload the postfix ++
operator as a class member?CustomData& operator++();
void operator++(CustomData);
CustomData operator++(CustomData);
CustomData operator++(int);
std::array<uint32_t, 50> my_array;
std::sort(my_array.begin(), my_array.end(),
[](uint32_t a, uint32_t b) {
return a < b;
})
lambda(uint32_t a, uint32_t b){
return a < b;
}
std::sort(my_array.begin(), my_array.end(), lambda);
std::sort(my_array.begin(), my_array.end(),
lambda(uint32_t a, uint32_t b){
return a < b;
})
lambda(uint32_t a, uint32_t b){
return a < b;
}
std::sort(my_array.begin(), my_array.end(), &lambda);
void std::mutex::lock(){
while(!this->try_lock());
}
void std::mutex::lock(){
return (this->try_lock());
}
void std::mutex::lock(){
while(1)
this->try_lock();
}
void std::mutex::lock(){
while(this->try_lock());
}
Note: variant of the question below.
std::mutex::lock()
std::mutex::try_lock()
lock()
has a higher privilege over try_lock()
. This means that you have a better chance of acquiring a mutex with lock()
.lock()
blocks if the mutex is not available, whereas try_lock()
returns whether the mutex is available or not.lock()
enforces preemption, whereas try_lock()
suggests preemption.try_lock()
returns with a corresponding code, whereas lock()
snatches the mutex from the thread that currently has it.Note: variant of the question above.
delete()
function.const
reference instead of declaring it as a regular object?int calculateMedian(const my_array& a)
const
reference is the only way to pass class instances to functions.const
qualifier forbids the code to modify the argument, so the programmer can rest assured that the source object will remain unchanged. / Alt.: The argument is passed as a reference, so if the passed my_array object is large, the program will require less time and memory.public: Sprite();
private: void Sprite();
public: void Sprite();
private: Sprite();
#pragma once
void *
, which works as a pointer to any type?void *
does not work for any type. The language does not allow assigning anything other than void
to a pointer to void *
.#include <iostream>
char str[20];
int main(){
std::cout << "What's your name? ";
str << std::cin
std::cout << "Hello, " << str;
return 0;
}
std::cin
and std::cout
are invalid. The correct names for the character input and output streams are cin
and cout
.str
is supposed to be used. That is &str
instead of str
.std::cin
and then flow (») into str
.int anInt = new int(11);
int* anInt = new int[11];
int anInt = new int[11];
int* anInt = new int(11);
long
?struct
union
enum
namespace
marks["Sinead"] = 22
marks["Sinead"].22
marks["Sinead"] -> 22
marks["Sinead"].value = 22
The std::sort function is a template. The programmer is free to enter the sorting algorithm in a function object as an argument.
Actually, std::sort takes only one argument, which is the container to be sorted.
std::sort operates on a template container. The compiler does not know how to relationally compare the values it contains, so a function must be provided to do the comparison.
std::sort will use the parameter function as an error handler. The function will be called if an error occurs.
#include <iostream>
int main() {
float a = 5.51;
int b = static_cast<int>(a);
std::cout << b;
}
6 will be printed on standard output, with no compilation warnings generated.
5 will be printed on standard output, with no compilation warnings generated.
6 will be printed on standard output, with compilation warnings generated.
5 will be printed on standard output, with compilation warnings generated.
#include <iostream>
using namespace std;
int main() {
int a=1;
cout<<(a++)*(++a)<<endl;
return 0;
}
cout << "Hello World";
System.out.println("Hello World");
print("Hello World");
<numeric>
<limit>
<limits>
<implementation>
void fact(int n) {
if (n <= 0)
return 0;
else
return 1;
}
int fact(int n) {
if (n <= 0)
return 1;
else
return (fact(n) * (n-1));
}
int fact(int n) {
if (n >= 0)
return 1;
else
return (fact(n-1) * n);
}
int fact(int n) {
if (n <= 0)
return 1;
else
return (fact(n-1) * n);
}
struct currencyDeal {
float price;
int quantity;
};
currencyDeal firstDeal;
union currencyDeal {
float price;
int quantity;
};
currencyDeal firstDeal;
struct currencyDeal {
float price;
int quantity;
};
union currencyDeal {
float price;
int quantity;
};
int checkConcatThreshold(string a, string b) {
return (a + b).length () > 120;
}
auto myVeryFirstLambda = [=] (string name) {
return "Hello " + name + "!";
};
myVeryFirstLambda = [&] (string name) {
return "Hello " + name + "!";
};
auto myVeryFirstLambda = [] (string name) {
return "Hello " + name + "!";
};
myVeryFirstLambda = [] (string name) {
return "Hello " + name + "!";
};
int x=10, a=-3;
X+=a;
Explanation : +=
means increasing value. So x += a
is equivalent to x = x + a
ofstream
to notify the operating system?int main()
{
cout « size_in_bits(21) « endl;
cout « size_in_bits('f') « endl;
cout « size_in_bits(32.1f) « endl;
cout « size_in_bits(32.1) « endl;
return 0;
}
template <typename T>
size_t size_in_bits(const T& a){
return sizeof(a)*8;
}
template size_t size_in_bits(const {int,float,double,char,long}& a){
return sizeof(a)*8;
}
template <typename T {int,float,double,char,long>
size_t size_in_bits(const T& a){
return sizeof(a)*8;
}
size_t size_in_bits(void * a){
return sizeof(a)*8;
}
#include <iostream>
#include <string>
using namespace std;
class Vehicle {
public:
string fuel = "none";
};
class MotorizedVehicle : public Vehicle {
public:
string fuel = "fossil";
};
class NextgenMotorizedVehicle : public MotorizedVehicle {
public:
string fuel = "hydrogen";
};
int main() {
MotorizedVehicle aCar;
cout << aCar.fuel;
return 0;
}
#include <iostream>
#include <stack>
int main()
{
std::stack<int> stack;
stack.push(1);
stack.push(2);
stack.push(3);
stack.pop();
stack.push(4);
stack.top();
stack.pop();
std::cout << stack.top();
}
#Detailed explanation:
Now here we are supposed to implement a stack data structure that follows the FILO or (First IN Last Out) principle, stack.push() -> pushes an element into the from the end array. stack.pop() -> removes an element from the end of the array. stack.top() -> Just gives us the topmost element of the array. Now following the sequences of push and pop: [1,2,3] then pop function is used, The newly formed array is: [1,2,4] then the top is used to retrieve the topmost element ‘4’ then again the pop function is used which removes 4. thus, the resulting array is: 1,2. Then it prints the topmost element (ie: 2).
void& operator ?:(const bool cond, const void& iftrue, const void& iffalse);
The ternary operator is not overloadable.
void& operator conditional(const bool cond, const void& iftrue, const void& iffalse);
void* operator ?:(const bool cond, const void* iftrue, const void* iffalse);
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
bool compare(char c1, char c2){
return tolower(c1) > tolower(c2); //LINE-1
}
int main(){
char arr1[20] = "C++ Program", arr2[20] = "C Program";
cout << lexicographical_compare(arr1, arr1+strlen(arr1), arr2, arr2+strlen(arr2),
compare);
return 0;
}
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int data[] = {1,2,3,4,5};
int key = 5;
if(binary_search(__________)) //LINE-1
cout << "found";
else
cout << "not found";
return 0;
}
#include <iostream>
#include <algorithm>
using namespace std;
int main () {
int data[] = {50, 30, 40, 10, 20};
sort (&data[1], &data[4]);
for (int i = 0; i < 5; i++)
cout << data[i] << " ";
return 0;
}
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int element[5];
for(int i = 1; i <= 5; i++)
*(element + i - 1) = i * 5;
rotate(element, element + 4, element + 5);
rotate(element, element + 1, element + 4);
for (int i = 0; i < 5; ++i)
cout << element[i] << " ";
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int size = 3, c = 65;
vector<char> vc(size, ’A’);
for (int i = 1; i <= 2; i++)
vc.push_back(65 + i);
vc.resize(10, 90);
vc.resize(8);
for (int i = 0; i < vc.size(); i++)
cout << vc[i] << " ";
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string s1 = "C++ ";
string s2 = "Program";
__________________; //LINE-1
cout << s1;
return 0;
}
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int data[] = { 1, 2, 3, 4, 5 };
for (int i = 0; i < 1; i++) {
int j = data[i];
replace(data, data + 5, j, *(_________________)); //LINE-1
}
for (int i = 0; i < 5; ++i)
cout << data[i] << " ";
return 0;
}
#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
int main(){
char str[10] = "123456789";
stack<char> s1, s2;
int i;
for(i = 0; i < strlen(str)/2; i++)
s1.push(str[i]);
for(i=i-1; i < strlen(str); i++)
s2.push(str[i]);
while (!s1.empty()) {
s2.push(s1.top()); s1.pop();
}
while (!s2.empty()) {
cout << s2.top(); s2.pop();
}
return 0;
}
int i = 5;
const int *p = &i;
int * const q = &i;
int const *r = &i;
int const * const s = &i;
*p = 10; //STMT-1
*q = 10; //STMT-2
*r = 10; //STMT-3
*s = 10; //STMT-4
#include <iostream>
using namespace std;
char add(char c1 = ’a’) { return c1; }
char add(char c1 = ’a’, char c2 = ’b’) { return c1 + c2 - ’a’;}
char add(char c1 = ’a’, int d1 = 100){ return c1 + d1 - ’a’; }
char add(char c1 = ’a’, char c2 = ’b’, char c3) { return c1 + c2 + c3 - ’a’; }
int main() {
char c = add(’o’, ’k’);
cout << c << endl;
return 0;
}
#include <iostream>
using namespace std;
#define SQR(x) (x)*(x)
int main() {
int a=3;
cout << SQR(a++) << endl;
return 0;
}
#include<iostream>
#define X 1
using namespace std;
int main(){
int i;
const int i1 = 2;
const int i2 = i1; //LINE-1
i2 = X;
i = i1;
i1 = i;
return 0;
//LINE-2
//LINE-3
//LINE-4
}
#include<iostream>
using namespace std;
int main(){
int a = 5;
int &b = a+1;
a = a*b;
cout << a << " " << b;
return 0;
}
#Detailed explanation: The error is occurring because it is trying to create a reference to a temporary value. In the line int &b = a+1; we are attempting to create a reference b to the result of the expression a + 1, which is a temporary value. References must be bound to an actual object, not a temporary value or an expression that does not have a memory location.
#include <iostream>
using namespace std;
int& func(int& i) { //LINE-1
return i = i+5;
}
int main() {
int x = 1, y = 2;
int& z = func(x);
cout << x << " " << z << " ";
func(x) = y;
cout << x << " " << z;
return 0;
}
#include <iostream>
using namespace std;
void compute(int n1, int n2, ________, ________){ //LINE-1
n3 = n1 + n2;
*n4 = n1 * n2;
}
int main(){
int a = 100, b = 200, c = 0, d = 0;
compute(a, b, c, &d); //LINE-2
cout << c << ", ";
cout << d;
return 0;
}
#include <iostream>
using namespace std;
int main() {
int a = 2, *b;
*b = 5;
int * const ptr; // LINE-1
// LINE-2
ptr = b;
cout << *ptr;
return 0;
}
<garbage value>
#include <iostream>
using namespace std;
void fun(int a = 5) { cout << a << endl; }
//LINE-1
int fun(int x = 10) { cout << x << endl; return 0; } //LINE-2
int main() {
fun();
return 0;
}
#include<iostream>
using namespace std;
struct complex{
int re, im;
void show(){ cout << re << " + i" << im; }
};
______________________________________{ //Line-1
c2.re = c1.re+c2.re;
c2.im = c1.im+c2.im;
return c2;
}
int main(){
struct complex c1={2,5},c2{3,-2};
struct complex t = c1 + c2;
t.show();
return 0;
}
#include<iostream>
using namespace std;
class myClass{
int pra = 5;
public:
int pub = 10;
void set_pr(int x){ pra = x; }
void set_pu(int x){ pub = x; }
};
int main(){
myClass m;
int a, b;
a = m.pra; //LINE-1
b = m.pub; //LINE-2
m.set_pr(100); //LINE-3
m.set_pu(200); //LINE-4
return 0;
}
class Test{
________:
int x;
________:
int y;
/* Some more code */
};
struct S {
int a { 10 };
int b { 42 };
};
S s { 1 };
std::cout << s.a << ", " << s.b;
struct C {
C(int x) : a(x) { }
int a { 10 };
int b { 42 };
};
C c(0);
struct Point { int x; int y; };
Point pt {.y = 10, .x = 11 };
std::cout << pt.x << ", " << pt.y;
struct User { std::string name = "unknown"; unsigned age { 0 }; };
User u { "John", 101 };
for (const pair<string, int>& elem : m)
A The loop properly iterates over the map, creating no extra copies.
B The loop will create a copy of each element in the map as the type of elem mismatches.
C The code won’t compile as a const pair cannot bind to a map.
auto x = 4000.22;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<"hello";
}
}
int a=10;
int k=++a;
int m=a++;
cout<<k+m;
Both ++a and a++ increase the value of a by 1 (ie: 11) and hence k+m becomes 22.
break
statement in a loop in C++?const
keyword when used with a variable?#include <iostream>
using namespace std;
class A{
public:
A(){
cout<<"Constructor called\n";
}
~A(){
cout<<"Destructor called\n";
}
};
int main(int argc, char const *argv[])
{
A *a = new A[5];
delete[] a;
return 0;
}
printf("1/2 = %f",(float)(1/2));
class my_class{
public: static int count;
}
constexpr
keyword in C++?constexpr
is used to specify that a variable is a constant pointer.constexpr
is used to indicate that an expression can be evaluated at compile-time, making it suitable for use in constant expressions.Ref(https://www.geeksforgeeks.org/template-metaprogramming-in-c/)
int matrix[3][3] = {{1, 2, 3},{4, 5, 6},{7, 8, 9}};
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
int a = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = a;
}
}