Chapter - 3: Graduating to C++

Point out the errors, if any, in the following programs:


C
Sections
1
Exercises

(a)

#include<iostream>

using namespace std;

int main()
{
	int i = 5;
	int &j = i;
	int &k = j;
	int &l = i;
	
	cout << i << j << k << l;
	
	return 0;	
}

No Error.


(b)

#include<iostream>

using namespace std;

int main()
{
	int a = 10, b = 20;
	long int c;
	
	c = a *long int(b);
	cout << c;
	
	return 0;	
}

Error: typecasting to long int makes confusing as they have space, so just wrap them in braces (long int). It will work well.


(c)

#include<iostream>

using namespace std;

int main()
{
	const int i = 20;
	cout << &i << &::i;
	
	return 0;	
}

Error: There's no global i, so ::i is not declared anywhere an error will be generated.


(d)

#include<iostream>

using namespace std;

int main()
{
	const int i = 20;
	cout << &i << &::i;
	
	return 0;	
}

Error: Can't assign 'G' to *p, as the string is constant and cannot be modified with a new value ('G').


(e)

#include<iostream>

using namespace std;

int main()
{
	enum result {first, second, third};
	result a = first;
	int b = a;
	result c = 1;
	result d = result(1);
	
	return 0;	
}

Error: enum variable result can only have values first, second or third, but assigning 1 to c.


(f)

#include<iostream>

using namespace std;

const int a = 124;
const int *sample();

int main()
{
	int *p;
	p = sample();
	return 0;	
}
const int *sample()
{
	return (&a);
}

Error: sample() is returning a const int* and assigning to a pointer of int* type, which is invalid.


(g)

#include<iostream>

using namespace std;

int a = 10;

int main()
{
	int a = 20;
	{
		int a = 30;
		cout << a << ::a << ::::a;
	}
	
	return 0;	
}

Error: :::: is not any valid operator.


(h)

#include<iostream>

using namespace std;

struct emp
{
	char name[20];
	int age;
	float sal;
};

emp e1 = {"Amol", 21, 2345.00};
emp e2 = {"Ajay", 19, 2300.00};

emp &fun();

int main()
{
	fun() = e2;
	cout << endl << e1.name << endl << e1.age << endl << e1.sal;
	return 0;	
}

emp &fun()
{
	emp e3 = {"Aditya", 21, 3300.75};
	return e3;
}

No Error
Warning: Returning emp, while the return type is emp&


(i)

#include<iostream>

using namespace std;

int main()
{
	char t[] = "String functions are simple";
	int l = strlen(t);
	cout <<l;
	return 0;	
}

Error: strlen() is not declared in this scope. To use string functions, include its header file <string>.


© 2021 Garbage Valuegarbage value logo