Difference between revisions of "ES101 - Lesson 7 : Functions with Pass-By-Value"

From Embedded Systems Learning Academy
Jump to: navigation, search
(Objective)
(Objective)
Line 5: Line 5:
  
 
You can view the following screencast to review this lesson, but should read through this material regardless :
 
You can view the following screencast to review this lesson, but should read through this material regardless :
<coming soon>
+
[http://www.youtube.com/watch?v=JBcHwsoEslI Functions in C/C++]
  
 
== Function Declaration and Definition ==
 
== Function Declaration and Definition ==

Revision as of 05:30, 16 March 2013

Objective

The objective of this lesson is to learn how to write functions which lets you partition and re-use portion(s) of your code. You will also learn the differences between local and global variables.

Functions provide a mean to partition your code into smaller blocks and also reduce repetitive code. So far, you were using main() which itself is a function. When you call functions from main(), the CPU begins to run the code inside the called function, and once the code inside the function is complete, it returns back to the caller, such as the main() function.

You can view the following screencast to review this lesson, but should read through this material regardless :

Function Declaration and Definition

Think of functions as modules which perform a specific task. Functions can take zero or more parameters as input but cannot return more than one output. Before we go into detailed, examples, let's learn the basics of how to declare and define functions. Declaring a function is simply telling the compiler how the function signature looks like. Defining a function tells the compiler the code that should be run when the function is called. A function should be declared before your main() and defined after the main().

/* Declare functions before main():
 *   -- void at beginning means no return type
 *  |                         ---- void here means no parameters
 *  |                        |       */
  void hello_world_function(void);

void main()
{
    // Call the function 3 times:
    hello_world_function();
    hello_world_function();
    hello_world_function();
}

// Define the function:
// Note: No semicolon after function name
void hello_world_function(void)
{
    printf("Hello World!\n");
}

Note that when you call a function, you simply call it by typing the function name followed by () (brackets). Now, let's get into more details of functions that perform useful tasks. See examples below:

// Function without parameters
void print_hello_world(void);

// Function with two integer parameters
void print_two_numbers(int a, int b);

// Function with two integer parameters that returns the sum of a+b
// Note that return type is changed from "void" to "int"
int print_two_numbers_get_sum(int a, int b);

int main()
{
    print_hello_world();
    print_two_numbers(1, 2);

    // You can also pass two integer variables:
    int a = 1;
    int b = 2;
    int sum = print_two_numbers_get_sum(a, b);

    // Note: returned value is "caught" and stored into "sum"
 
    printf("Sum = %i\n", sum);

    return 0;
}


void print_hello_world(void)
{
    printf("Hello World!\n");
}

// Function with two integer parameters
void print_two_numbers(int a, int b)
{
    printf("Numbers = %i and %i\n", a, b);
}

int print_two_numbers_get_sum(int a, int b)
{
    printf("Numbers = %i and %i\n", a, b);
    int sum = (a + b);

    // You must return an int 
    return sum;

    // You don't have to return a variable.
    // You can compute integer value and return it using: "return (a + b);"
}



Function Local Variables

In the example above, the variables inside main() have nothing to do with variables inside print_two_numbers. When main() provides its variables a and b, and these are completely separate variables from a and b of print_two_numbers(). In the example below, note that the variable a inside main() will remain 5 because test_function() is only settings its own variable called a to 0.

void test_function(int a);

int main(void)
{
    int a = 5;
    test_function(a);
    printf("a = %i\n", a);
}

void test_function(int a)
{
    // Only this function's a is being set to zero.
    a = 0;
}



Global Variables

Global variables can be accessed by all functions. To define a global variable, declare it outside the main() function just like you declare your functions. It is recommended that your global variable use all capital letters to distinguish it from local variables.

int MY_GLOBAL_VAR = 0;

void test_function();

int main(void)
{
    test_function();
    printf("MY_GLOBAL_VAR = %i\n", MY_GLOBAL_VAR);
}

void test_function()
{
    MY_GLOBAL_VAR = 0;
}


Summary

In summary, you should take away these points from this lesson:

  • Functions should be declared before main() and defined after main()
  • When main() passes its variables to a function, it provides "copies" of its variables.
    Even if the called function modifies the variables, it is only modifying its own private copy.
    Variables of main() will remain unaffected
  • Function can take as many inputs as you wish separated by a comma
  • Function can only return one variable using the return statement.


Assignment

Build Functions

  1. Build a function called hello_functions with the following properties:
    • Returns nothing (void)
    • Prints out “Hello, I am using functions!”
  2. Build a function called pow with the following properties:
    • Takes 2 integers (base, and power) as input
    • Returns base^power
      For example, 2^3 = 8, if base is 2, and power is 3, this function should return 8.
      Note: In order to calculate the power, you need to use a for loop. ^ doesn't work as a power symbol in C/C++.
  3. Build a function called calculate_percent with the following properties:
    • Takes 2 floating-point numbers called "score" and "max_score"
    • Returns a floating point number which is percentage of score and max_score.
  4. Build a function called print_line()
    • Takes a character that will be used to print a line
    • Takes the number of times to print the character
    • For example, if we call print_line('*', 10), it should print :
      ********** (Prints * ten times).
      Note that when you call this function, you need to provide a char in single quotes.

Exercise your Functions

  1. In your main(), call hello_functions five times.
  2. Exercise your pow() function:
    • Ask the user to input a base number
    • Ask the user to input the power
    • Compute base^power and output the result
  3. Ask the user for a midterm score, and the maximum score
    • Compute the percentage using calculate_percent() and print it out.
  4. Insert a line with your favorite character between each function call you make as dictated in the bullets above.



Sample Code

See the code samples of this lesson above to get started with this assignment.