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 commentMultiline 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>
#endifInclude 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>. Trysudo find /Library -name iostreamon 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
mainindicates 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 codemul()is called inmain().
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;
}Compile and Link
To compile the whole program:
g++ -c main.cpp
g++ -c mul.cpp
g++ main.o mul.o -o mulcl /c main.cpp
cl /c mul.cpp
link main.obj mul.obj /Fe:mul.exeQuestion: We can also compile it by g++ main.cpp mul.cpp -o mul, but why we prefer to compile them seperately?
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:
prepend the namespace onto the function name by using
::(scope resolution operator)mycode::foo();usingdirective: make the names in the namespace available in the current scopeusing namespace mycode; foo();usingdeclaration: make a specific name from a namespace available in the current scopeusing 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
}
- Avoid
usingglobal variables. - Global variables can be accessed from anywhere in the program, which can lead to unexpected behavior.
Similarly,
- avoid putting a
usingdirective orusingdeclaration 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::coutisstd::ostream. - Data sent to std::cout is first placed in an output buffer
- Output is not displayed immediately.
- Flushes the buffer when
std::endlor ‘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
std::endlwill flush the output buffer while\ndoes not.- Overuse of
std::endlcan degrade performance.- For example, use
\nin a loop to avoid flushing the buffer each time.
- For example, use
Input Stream
std::cinreads data from the standard input stream(typically the console/terminal).- The type of
std::cinisstd::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.
Link errors
- Undefined reference: e.g., function not found.
- Multiple definitions: e.g., duplicate symbol.
Runtime errors
- Division by zero
- Out of bounds array access
- …
References
- Mainly dapted from Prof. Shiqi Yu’s C++ lecture notes.
- Microsoft C++ documentation.
- cppreference.com.
- A tour of C++ by Bjarne Stroustrup, the creator of C++.
- Professional C++ by Marc Gregoire.
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.