Homework 6


Due : 9.30am, 13 July
  1. Consider the program listed below. List which of the 32 assignment statements will be considered valid and which invalid by a C++ compiler. For each invalid statement, state what the types of the expressions on either side of the assignment operator evaluate to (Hint: they will be different).
  2. Now indicate what the output will be if only valid statements were in the program (i.e. if we removed the invalid statements).
#include <iostream.h>

int main ()
{
	int a = 1;
	float b = 2.0;
	float *ap;
	int *bp;
			
	// 32 assignment statements	
	ap = a;  
	ap = &a;
	a = ap;
	a = ≈
	ap = b;
	ap = &b;
	b = ap;
	b = ≈
	bp = a;
	bp = &a;
	a = bp;
	a = &bp;
	bp = b;
	bp = &b;
	b = bp;
	b = &bp;
																				
	ap = a;
	ap = *a;
	a = ap;
	a = *ap;
	ap = b;
	ap = *b;
	b = ap;
	b = *ap;
	bp = a;
	bp = *a;
	a = bp;
	a = *bp;
	bp = b;
	bp = *b;
	b = bp;
	b = *bp;

	// output statement
	cout << "a = " << a << " and b = " << b << "\n";
	
	return 0;
}																	

Solution

	ap = a;   invalid: lhs=pointer to float, rhs=int
	ap = &a;  invalid: lhs=pointer to float, rhs=pointer to int 
	a = ap;   invalid: lhs=int,              rhs=pointer to float
	a = ≈  invalid: lhs=int,              rhs=pointer to pointer to float
	ap = b;   invalid: lhs=pointer to float, rhs=float
	ap = &b;  valid
	b = ap;   invalid: lhs=float,            rhs=pointer to float
	b = ≈  invalid: lhs=float,            rhs=pointer to pointer to float
	bp = a;   invalid: lhs=pointer to int,   rhs=int
	bp = &a;  valid						
	a = bp;   invalid: lhs=int,              rhs=pointer to int
	a = &bp;  invalid: lhs=int,              rhs=pointer to pointer to int
	bp = b;   invalid: lhs=pointer to int,   rhs=float
	bp = &b;  invalid: lhs=pointer to int,   rhs=pointer to float
	b = bp;   invalid: lhs=float,            rhs=pointer to int
	b = &bp;  invalid: lhs=float,            rhs=pointer to pointer to int
																				
	ap = a;   invalid: lhs=pointer to float, rhs=int
	ap = *a;  invalid: lhs=pointer to float, rhs=error!!
	a = ap;   invalid: lhs=int,              rhs=pointer to float
	a = *ap;  valid
	ap = b;   invalid: lhs=pointer to float, rhs=float 
	ap = *b;  invalid: lhs=pointer to float, rhs=error!!
	b = ap;   invalid: lhs=float,            rhs=pointer to float
	b = *ap;  valid
	bp = a;   invalid: lhs=pointer to int,   rhs=int
	bp = *a;  invalid: lhs=pointer to int,   rhs=error!!
	a = bp;   invalid: lhs=int,              rhs=pointer to int
	a = *bp;  valid
	bp = b;   invalid: lhs=pointer to int,   rhs=float
	bp = *b;  invalid: lhs=pointer to int,   rhs=error!!
	b = bp;   invalid: lhs=float,            rhs=pointer to int
	b = *bp;  valid

Output: a = 2 and b = 2


Last updated : 13 July 2000 10.33pm