课程: Complete Guide to C Programming Foundations

Understanding functions

- [Instructor] It's possible to write code that uses only C language keywords, but to really program you use a function. A function is a programming machine that does something like a mini program. The function can take input, the function can generate output. It can do both, and it can do neither. The C library comes with a host of built-in functions. These are prototyped in the various header files, but the functions code is in the libraries mixed into your program by the linker. You use these library functions, but you can also create your own functions to perform specific tasks. All C programs have and use at least one function. The main function where code execution starts like variables all C functions have a data type. The data type for the main function is integer int shown here. This type reports which kind of value, if any, the function returns. The main function here must generate an integer value, which is set by the return statement at line seven. A functions data type and its output must match. This exercise file contains five functions, each of a different data type. The valchar function returns a character, so its type is char, valint returns an integer, valfloat returns a floating point value, valdouble returns a double value and valvoid returns nothing. It's a void function, regardless of the type functions in C return only a single value, the return keyword sends the value back to the calling statement. For the main function, its integer value is returned to the operating system. Functions that accept input have the values listed in their parentheses. These are called parameters or arguments. Here, the repeat function accepts a single argument. An integer value, variable R represents the value passed within the function. At line 15 the repeat function is called, its argument specified in parentheses, the argument can be a literal value, variable or expression, but the value must match the functions argument data type integer here. A function can accept any number of arguments. Here the total function accepts five arguments, each with a data type and variable name. The function is called at line 17 from within the printf function with arguments specified. The title function is a character pointer type returning a string. Its argument list is void. It has no arguments. It's called at line 16 where no arguments are listed. The functions value is available after the function call. It can be stored in a variable or used immediately as you see in this code, in the printf statement, in, out, or not at all this is how functions in C consume and return values.

内容