Posts

Showing posts with the label function

Variable argument function in Golang

Variable argument function in Golang PROGRAM: package main import "fmt" func main () { myfunc ( 10 , 20 , 30 ) fmt . Printf ( " " ) myfunc ( 52 , 43 , 24 , 78 , 23 ) fmt . Printf ( " " ) vals := [] int { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 } myfunc ( vals ...) } func myfunc ( args ... int ) { for ind , val := range args { fmt . Println ( ind , "->" , val ) } } OUTPUT: 0 -> 10 1 -> 20 2 -> 30 0 -> 52 1 -> 43 2 -> 24 3 -> 78 4 -> 23 0 -> 1 1 -> 2 2 -> 3 3 -> 4 4 -> 5 5 -> 6 6 -> 7 7 -> 8 download  file  now

va list and variadic function

va list and variadic function C: Ellipsis operator (�) : printf refer to: http://linuxprograms.wordpress.com/2008/03/07/c-ellipsis-operator-printf/ Ever imagined how printf works, even though we are able to pass a number of arguments to it. If we design a function which takes two arguments and pass three parameters, we are bound to get this error �too many arguments to function�i.e., suppose we have a function int fun2(int a, int b) and we call the function fun2(2,3,4) we are sure to get the above error. So the question is how printf / scanf works with variable number of arguments? This is because C has a feature called ellipsis (�) by which you are able to pass variable number of arguments? So the prototype of printf is int printf(const char *str,...) But the next question is how then can we access the arguments in the function. This can be done by the power of pointers. Let�s take a pointer which points to the last argument before � and depending on the next arguments of ...