Monday, November 15, 2021

(C++) How to pass a variable type to a function

 E.g If you need to pass info like this:

void foo(type){
    // Other actions based on type
    cout << sizeof(type);

This cannot be done i.e. the type cannot be passed as a parameter since it is not a object and they do not exist at run time. They are only used by the compiler for type information building into the code. This can be instead fullfilled by templatinzing the function.

A template behaves in the following way:

template <typename T>

void foo(other_args) {

    // Other relevant data.

    T  somevar;

    cout << sizeof(somevar) << "    " <<sizeof(T);


Typenames can be also used to templatize classes in a similar fashion. 

Programming: Find location of Stack, Heap and current memory

 Simple code:

#include <stdio.h>

#include <stdlib.h>

int main(int argc, char *argv[]) {

    printf("location of code : %p\n", main);

    printf("location of heap : %p\n", malloc(100e6));

    int x = 3;

    printf("location of stack: %p\n", &x);

    return 0;


Note that %p prints the address of the pointer.