Sunday, June 21, 2009

Week 2

This week, I witnessed a plethora of interesting subtleties of C++:
i) the pointers, and the references;
ii) types of variables
iii) templates

It's interesting how placement of '&' and '*' can give a whole different meaning to variables. For example,


int i = 2;
int* p = j; // does not compile
int* p = &j; /* initializes a pointer 'p' pointing to integer 'j' */


/*increments the memory address which could lead to illegal memory access */
++p;

//increments j
++*p;


Now consider,

int k = 4;
int& r = k; /* r serves as an alias of k */

//same as ++k
++r;


Using '&' for references frees the programmer from de-referencing the variable like in pointers. However, once the reference is defined, it is glued to the variable it references; while the pointer can be changed to point to other variable (if not declared as constant).

Things become interesting when using '&' and '*' together. While, int&* x isn't valid, but


int i = 2;
int* p = i;
int*& r = p; //alias for pointer 'p'


Next, we studied about different types of variables, and compared their scopes, lifetimes, and time-line when they are allocated, and initialized. "non-static local variable" and "static local variable" both differ except in terms of their scope. Contrarily, "non-static global variable" and "static global variable" differ only in their scopes. "Non-static global variable" has the scope of whole program, while "static global variable" has the file scope. The program will compile even if a static variable is used in other file using extern, but will fail during the linkage.


C++ has a powerful feature of creating templates. But with power, comes the responsibility; and here the responsibility is of the programmer to fully understand how to create classes considering the types of variables and their instances to be created. For example,


template <typename T>
struct A {
static T sv0; // creates one sv0 per T
static int sv1; // still creates one sv1 per T
T v0; // create 1 v0 per instance of A
}

Finally, we studied how different function declaration give or don't give access to the original data.

For example,
void f(int v) {++v;} // creates a local copy of the argument
void g(int* p) {++*p;} // changes the original data
void h(int& r) {++r;} // changes the original data

No comments:

Post a Comment