Charles Tritt / Mbed OS 21_FuncEx_v5
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /*
00002 Project: 21_FuncEx_v5
00003 File: main.cpp
00004 
00005  This simple program demonstrates that C passes arguments by value.
00006  
00007  See http://www.csie.ntu.edu.tw/~r92094/c++/VT100.html and/or 
00008  https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797 for escape 
00009  sequences.
00010  
00011  Written by: Dr. C. S. Tritt; Last revised 10/11/21 (v. 1.2)
00012 */
00013 #include "mbed.h"
00014 
00015 // Function definitions are typically in .h files are more commonly that are 
00016 // included here.
00017 int myFunc(int x, int y); // Function declaration required.
00018 
00019 Serial pc(USBTX, USBRX, 9600); // Create Serial object.
00020 
00021 const char ESC = 27; // ESC character for ANSI escape sequences.
00022 const int DELAY = 2000; // Loop delay in mS.
00023 
00024 int main() {
00025     while(true) {
00026         // Clear screen & move cursor to upper left ANSI/VT100 sequence.
00027         pc.printf("%c[2J", ESC); pc.printf("%c[H", ESC);
00028         // Start of display code.
00029         pc.printf("In function demo main...\n");        
00030         int a = 5; // Create and initialize a.
00031         pc.printf("a = %d\n", a); // Display a.
00032         int b = 6; // Create and initialize b.
00033         pc.printf("b = %d\n", b); // Display b.
00034         pc.printf("About to call my function.\n");
00035         int c = myFunc(a, b); // Call my function.
00036         pc.printf("Function has returned.\n");
00037         pc.printf("a = %d\n", a); // Redisplay a.
00038         pc.printf("b = %d\n", b); // Redisplay b.               
00039         pc.printf("c = %d\n", c); // Display b.
00040         ThisThread::sleep_for(DELAY); // Pause for DELAY mS.
00041     }
00042 }
00043 
00044 int myFunc(int x, int y) { // Function definition. Often in separate files!
00045     int z = x + y;
00046     // Changing parameter values here won't change argument values in main!
00047     x = 50;
00048     pc.printf("x = %d\n", x); // Generally don't put I/O in regular functions.
00049     y = 100;
00050     pc.printf("y = %d\n", y); // Generally don't put I/O in regular functions.
00051     return z; // Explicit return is required in C/C++. 
00052 }