Programming in C

(Barry) #1

134 Chapter 8 Working with Functions


Based upon this discussion, you can understand that when the value of guess^2 - xis
passed to the absoluteValuefunction and assigned to the formal parameter x, this
assignment has absolutely noeffect on the value of xinside the squareRootfunction.

Declaring Return Types and Argument Types


As mentioned previously, the C compiler assumes that a function returns a value of type
intas the default case. More specifically, when a call is made to a function, the compiler
assumes that the function returns a value of type intunless either of the following has
occurred:


  1. The function has been defined in the program before the function call is encoun-
    tered.

  2. The value returned by the function has been declaredbefore the function call is
    encountered.
    In Program 8.8, the absoluteValuefunction is defined before the compiler encounters
    a call to this function from within the squareRootfunction.The compiler knows, there-
    fore, that when this call is encountered, the absoluteValuefunction will return a value
    of type float.Had the absoluteValuefunction been defined afterthe squareRoot
    function, then upon encountering the call to the absoluteValuefunction, the compiler
    would have assumed that this function returned an integer value. Most C compilers
    catch this error and generate an appropriate diagnostic message.
    To be able to define the absoluteValuefunction afterthe squareRootfunction (or
    even in another file—see Chapter 15), you must declarethe type of result returned by the
    absoluteValuefunction beforethe function is called.The declaration can be made inside
    the squareRootfunction itself, or outside of any function. In the latter case, the declara-
    tion is usually made at the beginning of the program.
    Not only is the function declaration used to declare the function’s return type, but it
    is also used to tell the compiler how many arguments the function takes and what their
    types are.
    To declare absoluteValueas a function that returns a value of type floatand that
    takes a single argument, also of type float, the following declaration is used:
    float absoluteValue (float);
    As you can see, you just have to specify the argument type inside the parentheses, and
    not its name.You can optionally specify a “dummy” name after the type if you want:
    float absoluteValue (float x);
    This name doesn’t have to be the same as the one used in the function definition—the
    compiler ignores it anyway.
    A foolproof way to write a function declaration is to simply use your text editor to
    make a copy of the first line from the actual definition of the function. Remember to
    place a semicolon at the end.

Free download pdf