Introduction
Hello World Program
// C++ example in C++11
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
{"Hello C++ World!"};
string msg << msg << endl;
cout 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>
. Trysudo 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;
<< "Pick two integers:";
cout >> a;
cin >> b;
cin = mul(a, b);
result << "The result is " << result << endl;
cout 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;
<< "Pick two integers:";
cout >> a;
cin >> b;
cin = mul(a, b);
result << "The result is " << result << endl;
cout return 0;
}
Compile and Link
To compile the whole program:
g++ -c main.cpp
g++ -c mul.cpp
g++ main.o mul.o -o mul
/c main.cpp
cl /c mul.cpp
cl .obj mul.obj /Fe:mul.exe link main
Question: 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)::foo(); mycode
using
directive: make the names in the namespace available in the current scopeusing namespace mycode; (); foo
using
declaration: 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
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 orusing
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
isstd::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
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.
- For example, use
Input Stream
std::cin
reads data from the standard input stream(typically the console/terminal).- The type of
std::cin
isstd::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
.