Predefined macros variable argument lists

Nasza ocena:

3
Wyświetleń: 483
Komentarze: 0
Notatek.pl

Pobierz ten dokument za darmo

Podgląd dokumentu
Predefined macros variable argument lists - strona 1 Predefined macros variable argument lists - strona 2 Predefined macros variable argument lists - strona 3

Fragment notatki:

Predefined macros variable argument lists  Header file:  Macros: void va_start(va_list ap, lastfix); type va_arg(va_list ap, type); void va_end(va_list ap);  Type: va_list  Purpose - to provide a way for defining functions of unknown number of parameters  Idea - the function gets a pointer to the first parameter and reads subsequent parameters using this pointer  Drawback - the programmer is responsible for knowing the number and types of these parameters  Existing example - the function printf  How it works - the user always provides a string defining the rest of parameters passed to the function - the function printf assumes, that the list of parameters exactly follows the string - in case of a mistake in the string or parameters, the function may fail and crash the program  Own function with variable argument list #include #include /* calculate sum of a 0 terminated list */ void sum(char *msg, ...) { int total = 0; va_list ap; int arg; va_start(ap, msg); while ((arg = va_arg(ap,int)) != 0) { total += arg; } printf(msg, total); va_end(ap); } int main() { sum("The sum 1+2+3+4 is %d\n", 1,2,3,4,0); return 0; } ... zobacz całą notatkę



Komentarze użytkowników (0)

Zaloguj się, aby dodać komentarz