1 / 6

Variable Arguments in C

Variable Arguments in C. System Software Fall 2013. A short example. #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; /* for atoi() */ int main(int argc, char *argv[]) { int m,n; if (argc != 4) { printf(&quot;Usage: %s m n filename<br>&quot;,argv[0]);

doyle
Download Presentation

Variable Arguments in C

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Variable Arguments in C System Software Fall 2013

  2. A short example #include <stdio.h> #include <stdlib.h> /* for atoi() */ int main(int argc, char *argv[]) { int m,n; if (argc != 4) { printf("Usage: %s m n filename\n",argv[0]); return 1; /* If the input does not match the expected */ } m = atoi(argv[1]); /* convert strings to integers */ n = atoi(argv[2]); printf("%s received m=%i n=%i filename=%s\n",argv[0],m,n,argv[3]); return 0; }

  3. Rules For Variable Arguments • main() is passed two arguments from the shell: an integer and a pointer • Traditionally named • Int argc (array count) • char *argv[] (argument vector) • The name of the program is always passed as an argument, so argc is atleast 1.

  4. Psuedo Code Using Variable Arguments For(i = 1; i <= arc; i++) { if argv[i] == flag execute some code, or set some condition }

  5. Another Example #include <stdio.h> int main (int argc, char *argv[]) { int i=0; printf("\ncmdline args count=%s", argc); /* First argument is executable name only */ printf("\nexe name=%s", argv[0]); for (i=1; i< argc; i++) { printf("\narg%d=%s", i, argv[i]); } printf("\n"); return 0; }

  6. Output • $ ./cmdline_basic test1 test2 test3 test4 1234 56789cmdline args count=7 exe name=./cmdline_basic arg1=test1 arg2=test2 arg3=test3 arg4=test4 arg5=1234 arg6=56789

More Related