How can I pass a variable type to a function? like this:
void foo(type){ cout << sizeof(type); }
You don't actually pass a type to a function here, but create new code for every time you use it. To avoid doubt: ({...}) is a "statement expression", which is a GCC extension and not standard C.
variable is in the scope of startFunction and its value is passed to adding function. variable2 is only in the scope of function adding where the value of 1 is added to the value of variable. you return the value of variable2 but there is no variable to receive that value.
Both local and global variables are passed to functions by value in C. If you need to pass by reference, you will need to use pointers.
You can't pass types like that because types are not objects. They do not exist at run time. Instead, you want a template, which allows you to instantiate functions with different types at compile time:
template <typename T> void foo() { cout << sizeof(T); }
You could call this function with, for example, foo<int>()
. It would instantiate a version of the function with T
replaced with int
. Look up function templates.
As Joseph Mansfield pointed out, a function template will do what you want. In some situations, it may make sense to add a parameter to the function so you don't have to explicitly specify the template argument:
template <typename T> void foo(T) { cout << sizeof(T) }
That allows you to call the function as foo(x)
, where x
is a variable of type T. The parameterless version would have to be called as foo<T>()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With