Post

[C++] Chap 03 - Functions

[C++] Chap 03 - Functions

Functions

  • A function can have any finite number of arguments of varying data types / No function has more than one value returned (One or zero)
  • Predefined functions : #import <cmath>, sqrt(x), pow(x, i), fabs(x), floor(x), ceil(x), round(x)

Random number generator

  • rand() : takes no arguments, returns a uniform random integer btw 0 & RAND_MAX
  • #includ <cstdlib>
  • srand() : seed

Time

  • #include <ctime>
  • to return current time (elapsed in seconds since 1970.01.01) : time(NULL)

Components of Function Use

  • Function declaration / Prototype
  • Function Definition (implementation)
  • Function Call

Function Declaration / Prototype

1
2
3
4
<rtn_type> FcnName(<formal-param-list>);
double totalCost(int num, double price);
// or
double totalCost(int, double);
  • Designates the type of the “return val”, “name of func”, “number of arguments”, “type of formal parameters”
  • Placed before any calls to the function (above the main)
  • Formal parameter names are not needed : can only present data types of params.

Function definition

  • Entire implementation of function is called function definition, lines inside the bracket is called function body.

  • Can be placed after or before the main function.
  • In case of before, function declaration can be omitted
  • Can also be placed in a seperate file (another .cpp or for declaration, .h or .hpp)
  • Functions are equal, no function is a ”part” of another.
  • (formal) Parameters : Memory placeholders for data sent in

Function call

  • Arguments at function call : actual arguments
  • Function arguments can be literals, variables, expressions, or their combination

Simple example : multiple cpp files and header

Parameter vs Argument

  • Often used interchangably but technically param is “formal” piece while argument is “actual”
  • Formal (params/args) : in function declaration, header
  • Actual (params/args) : in function call

Return statement

  • return is optional statement for void function ( Closing bracket } implicitly return control from void function)
  • Return type other than void MUST have return statement. (except for main())

Main

  • Operating system calls main()
  • should return int or void
  • omitting return in main()is possible

Scope rules

  • Local variables : declared inside the body of given function / available only within that func.
  • Global variables : if declared outside function body
  • Global constants : const double TAXRATE=0.05; Declared globally so all functions can use it.
  • variables declared with const inside the function is also follows scope rules
This post is licensed under CC BY 4.0 by the author.