New example. Initial version.

main.cpp

Committer:
CSTritt
Date:
2021-10-11
Revision:
111:956b1c606b66
Parent:
110:22b71c32c5e1
Child:
112:c7c727d92f2a

File content as of revision 111:956b1c606b66:

/*
Project: 21_FuncEx_v5
File: main.cpp

 This simple program demonstrates that C passes arguments by value.
 
 See http://www.csie.ntu.edu.tw/~r92094/c++/VT100.html and/or 
 https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797 for escape 
 sequences.
 
 Written by: Dr. C. S. Tritt; Last revised 10/11/21 (v. 1.2)
*/
#include "mbed.h"

// Function definitions are typically in .h files are more commonly that are 
// included here.
int myFunc(int x, int y); // Function declaration required.

Serial pc(USBTX, USBRX, 9600); // Create Serial object.

const char ESC=27; // ESC character for ANSI escape sequences.
const int DELAY = 2000; // Loop delay in mS.

int main() {
    while(true) {
        // Clear screen & move cursor to upper left ANSI/VT100 sequence.
        pc.printf("%c[2J", ESC); pc.printf("%c[H", ESC);
        // Start of display code.
        pc.printf("In function demo main...\n");        
        int a = 5; // Create and initialize a.
        pc.printf("a = %d\n", a); // Display a.
        int b = 6; // Create and initialize b.
        pc.printf("b = %d\n", b); // Display b.
        pc.printf("About to call my function.\n");
        int c = myFunc(a, b); // Call my function.
        pc.printf("Function has returned.\n");
        pc.printf("a = %d\n", a); // Redisplay a.
        pc.printf("b = %d\n", b); // Redisplay b.               
        pc.printf("c = %d\n", c); // Display b.
        ThisThread::sleep_for(DELAY); // Pause for DELAY mS.
    }
}

int myFunc(int x, int y) { // Function definition. Often in separate files!
    int z = x + y;
    // Changing parameter values here won't change argument values in main!
    x = 50;
    pc.printf("x = %d\n", x); // Generally don't put I/O in regular functions.
    y = 100;
    pc.printf("y = %d\n", y); // Generally don't put I/O in regular functions.
    return z; // Explicit return is required in C/C++. 
}