Introduction

Hello World Program

// C++ example in C++11
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main() {
    string msg {"Hello C++ World!"};
    cout << msg << endl;
    return 0;
}

Don’t worry if you don’t understand everything.

We will revisit these concepts in detail later in the course.

Comment

A message that exists for the programmer only and is ignored by the compiler.

Two forward slashes:

// this is a comment

Multiline comments start with /* and end with */.

/* This is a multiline comment.
   The compiler will ignore it.
*/

Preprocessor Directives

  • The preprocessor is executed before the compilation.
  • Preprocessing directives begin with a # character.
  • Each directive occupies one line.
  • Some common preporcessing instruction: define, include, if, ifdef, ifndef, else, pragma
// include directive
#include <iostream>

// the current source file to be 
// included only once
#pragma once

// macro
#define PI 3.1415926535

// conditional inclusion
#if defined(_OPENMP)
#include <omp.h>
#endif

Include directive

  • #include <header> searches for a header and replaces the directive by the entire contents of the header.
    • These headers are provided by the library maintainer.
    • Example: C++ Standard Library headers like <iostream>. Try sudo find /Library -name iostream on OSX.

  • #include "file" searches for a header file and replaces the directive by the entire contents of the header file.
    • This file generally includes the current path.
    • If not found, interprets the directive as a header inclusion.

The main() Function

The program starts from the main function.

int main() {
    // some operationf
    return 0;
}
  • The return type of main() is an int, indicating the result status of the program.

  • A nonzero value from main indicates failure.

  • The main() function either takes no parameters or takes two parameters as follows

    int main(int argc, char** argv) {...} // we will go back to this later
  • {} indicate the start and the end of the function body.

Functions

#include <iostream>

using namespace std;

int mul(int a, int b){
    return a * b;
}

int main(){
    int a, b;
    int result;
    cout << "Pick two integers:";
    cin >> a;
    cin >> b;
    result = mul(a, b);
    cout << "The result is " << result << endl;
    return 0;
}
  • main(): called by startup code
  • mul() is called in main().

Function prototypes and definitions

  • function prototypes/declaration normally are put into head files (*.h; *.hpp).

    int mul(int a, int b);
  • function definitions normally are in source files (*.c; *.cpp).

    int mul(int a, int b){
      return a * b;
    }

Separate the source code into multiple

// mul.hpp
#pragma once

int mul(int a, int b);

// mul.cpp
#include "mul.hpp"

int mul(int a, int b){
    return a * b;
}
//main.cpp
#include <iostream>
#include "mul.hpp"

using namespace std;

int main() {
    int a, b;
    int result;
    cout << "Pick two integers:";
    cin >> a;
    cin >> b;
    result = mul(a, b);
    cout << "The result is " << result << endl;
    return 0;
}

Namespaces

Namespaces address the problem of naming conflicts between different pieces of code.

  • Group related declarations together
  • Prevent naming clashes with other code

To declare a namespace, we use the namespace keyword.

namespace mycode {
    void foo() {
        std::cout << "foo() called in the mycode namespace" << std::endl;
    }
}

Using a namespace

There are three ways to access the foo() function:

  1. prepend the namespace onto the function name by using ::(scope resolution operator)

    mycode::foo();
  2. using directive: make the names in the namespace available in the current scope

    using namespace mycode;
    foo();
  3. using declaration: make a specific name from a namespace available in the current scope

    using mycode::foo;
    foo();

Scope

A program element’s name (e.g., class, function, variable) is only visible in certain parts of your program.

Local scope: names declared within a function or lambda, including parameters.

void exampleFunction() {
    int localVar = 10; // local scope
    auto lambda = [](int param) { // local scope
        return param * 2;
    };
}

Global scope: names declared outside any class, function, or namespace.

// a cpp file
int globalVar = 20; // global scope

void anotherFunction() {
    // can access globalVar here
}

Warning
  • Avoid using global variables.
  • Global variables can be accessed from anywhere in the program, which can lead to unexpected behavior.

Similarly,

  • avoid putting a using directive or using declaration in a header file.
  • Otherwise, you force it on everyone who includes your header file.

I/O Stream

Output Stream

std::cout writes data to the standard output stream(typically the console/terminal).

  • << (put to) operator writes its second argument onto its first.
  • The type of std::cout is std::ostream.
  • Data sent to std::cout is first placed in an output buffer
    • Output is not displayed immediately.
    • Flushes the buffer when std::endl or ‘std::flush’ is encountered.
    • Flushes the buffer when the buffer is full or when the program ends.

A program demonstrates std::cout does not display the output immediately.

#include <iostream>
#include <thread>
#include <chrono>

int main() {
    std::cout << "Processing...";
    std::this_thread::sleep_for(std::chrono::seconds(3));
    std::cout << "done!" << std::endl;
    return 0;
}

On most systems, the “Processing…” will be displayed after 3 seconds.

Some escape sequences

  • \n: newline
  • \t: tab
  • \\: backslash
  • \": double quote
Note
  • std::endl will flush the output buffer while \n does not.
  • Overuse of std::endl can degrade performance.
    • For example, use \n in a loop to avoid flushing the buffer each time.

Input Stream

  • std::cin reads data from the standard input stream(typically the console/terminal).
  • The type of std::cin is std::istream.
  • Similarly, data read from std::cin is placed in an input buffer.

Errors

Compile-time errors

  • Syntax errors: e.g., missing semicolon, incorrect parentheses.
  • Declaration errors: e.g., redeclaration of a variable.

Runtime errors

  • Division by zero
  • Out of bounds array access

References

Install VS Code

  • Download and install VS Code.
  • Install the C++ extension.
  • If you are using brew, you can install it by brew install vscode.