Posts Tagged ‘interviews’
Implementing sizeof operator
Everyone knows how to use a size of operator, but very few knows how to implement it correctly. This is a frequently asked question in interviews. The actual size of operator accepts both keyword, variables and class and struct instances, we will write two versions of size of with one accepting keywords and the other accepting variables, class and struct instances.
//Keywords
#define K_SIZE_OF(X) ( (X*)0 + 1 )
Basically, here you are trying to cast the 0th location in the memory to type X. If X is passed as int, the first four bytes will be interpreted as int and four will be returned. If it is X is a char, one will be returned and so on.
//Variables, class and struct instances
#define V_SIZE_OF(X) ( (&X+1) - (&X) )
Here, we are trying to move the address of the variable/instance by SIZE bytes and subtracting it from the current address which will actually give us SIZE back.
:-)