ch3-Modifiers (Pointers and references, void pointer)

Chapter_3     Exercise_3-7 Scope     Exercise_3-8







CONTENTS:     AllDefinitions.cpp     VoidPointer.cpp     CastFromVoidPointer.cpp




AllDefinitions.cpp     TCP1, p. 153-154         download


// All possible combinations of basic data types,
// specifiers, pointers and references (as modifiers)

void f1(char c, int i, float f, double d);
void f2(short int si, long int li, long long int lli, long double ld);
void f3(unsigned char uc, unsigned short int usi, unsigned int ui,
unsigned long int uli, unsigned long long int ulli);
void f4(char* cp, int* ip, float* fp, double* dp);
void f5(short int* sip, long int* lip, long long int* llip, long double* ldp);
void f6(unsigned char* ucp, unsigned short int* usip, unsigned int* uip,
unsigned long int* ulip, unsigned long long int* ullip);
void f7(char& cr, int& ir, float& fr, double& dr);
void f8(short int& sir, long int& lir, long long int& llir, long double& ldr);
void f9(unsigned char& ucr, unsigned short int& usir, unsigned int& uir,
unsigned long int& ulir, unsigned long long int& ullir);

int main()
{
return 0;
}
/*
g++ AllDefinitions.cpp -o AllDefinitions
./AllDefinitions
*/











VoidPointer.cpp     TCP1, p. 154         download


int main()
{
void* vp;
char c;
int i;
float f;
double d;
// The address of ANY type can be assigned to a void pointer:
vp = &c; // no cast required
vp = &i;
vp = &f;
vp = &d;

return 0;
}
/*
g++ VoidPointer.cpp -o VoidPointer
./VoidPointer
*/











CastFromVoidPointer.cpp     TCP1, p. 154-155         download


#include <iostream>
using std::cout;
using std::endl;

int main()
{
int i = 99;
void* vp = &i;
// cout << "i = " << i << ", *vp = " << // Can't dereference a void pointer:
// *vp << endl; // Compile error: `void*' is not a pointer-to-object type
cout << "i = " << i << ", *((int*)vp) = " <<
*((int*)vp) << endl; // Must cast back to `int*' before dereferencing
// *vp = 3; // Compile-time error: `void*' is not a pointer-to-object type
*((int*)vp) = 3; // Must cast back to `int*' before dereferencing
cout << "i = " << i << ", *((int*)vp) = " <<
*((int*)vp) << endl; // Must cast back to `int*' before dereferencing

char c = 'A';
vp = &c; // no cast needed here
cout << "c = '" << c << "', *((char*)vp) = '" << *((char*)vp) << '\'';
cout << endl;
// *vp = 'C'; // Compile-time error: `void*' is not a pointer-to-object type
*((char*)vp) = 'C';
cout << "c = '" << c << "', *((char*)vp) = '" << *((char*)vp) << "'";
cout << endl;

return 0;
}
/*
g++ CastFromVoidPointer.cpp -o CastFromVoidPointer
./CastFromVoidPointer
i = 99, *((int*)vp) = 99
i = 3, *((int*)vp) = 3
c = 'A', *((char*)vp) = 'A'
c = 'C', *((char*)vp) = 'C'
*/









Chapter_3     Exercise_3-7 BACK_TO_TOP Scope     Exercise_3-8



Comments

Popular posts from this blog

Contents