C Lecture 4
[Previous Lecture]
[Lecture Index]
[Next Lecture]
Function Prototypes
-
Always tell compiler about identifiers before
using them.
Thus, delcare variables before using them
and declare functions before calling them
-
function declarations aka prototypes
-
prototypes often put in header files
Syntax:
return-type func-name(arg-1-type arg-1-name,
arg-2-type arg-2-name, etc );
(i.e., same as function preamble, but semi-colon instead of function body)
Example:
#include <stdio.h>
char *my_fgets(char *b, int bsize, FILE *fp);
int
main()
{
char buf[1024];
while (fgets(buf, sizeof(buf), stdin))
printf("%s\n", buf);
return 0;
}
char *
my_fgets(char *b, int bsize, FILE *fp)
{
...
}
Character classification routines (ctype.h)
#include <ctype.h>
- isalpha(char c): is c an alphabetic character?
- isupper(char c): is c an upper case alphabetic?
- islower(char c): is c an lower case alphabetic?
- isspace(char c): white space (space, tab, \n)?
- isdigit(char c): is c a decimial digit?
- isxdigit(char c): is c a hexidecimal digit?
- isalnum(char c): is c an letter or a digit?
- toupper(char c): return upper case version of c
- tolower(char c): return lower case version of c
#include <ctype.h>
int
atoi(char *str)
{
char *p;
int num;
int sign = 1;
for (p = str; isspace(*p); p++)
;
if (*p == '-') {
sign = -1;
p++;
}
for (num = 0; isdigit(*p); p++)
num = num * 10 + (*p - '0');
return sign * num;
}
Command Line Arguments
Example:
#include <stdio.h>
int
main(int argc, char *argv[])
{
int i;
for (i = 1; i < argc; i++) {
if (i > 1)
printf(" ");
printf("%s", argv[i]);
}
printf("\n");
return 0;
}
[Previous Lecture]
[Lecture Index]
[Next Lecture]