A simple "die" function for C - example of variable number of arguments
This simple function illustrates receiving and sending out a
variable number of arguments in C
using <stdarg.h>
.
#include <stdio.h> #include <stdarg.h> #include <stdlib.h> static void die (int line_number, const char * format, ...) { va_list vargs; va_start (vargs, format); fprintf (stderr, "%d: ", line_number); vfprintf (stderr, format, vargs); fprintf (stderr, ".\n"); va_end (vargs); exit (1); } int main (int argc, char ** argv) { if (argc == 1) { die (__LINE__, "%s: I need more arguments", argv[0]); } return 0; }
The output of this program looks like this:
19: ./die: I need more arguments.
Here is the makefile to compile and run this and print the example:
die.txt: die -./die > $@ 2>&1 die: die.c cc -Wall -g -o $@ die.c clean: rm -f die die.txt
Copyright © Ben Bullock 2009-2024. All
rights reserved.
For comments, questions, and corrections, please email
Ben Bullock
(benkasminbullock@gmail.com).
/
Privacy /
Disclaimer