Introduction To C Part 1
Introduction To C Part 1
Provides:
Easy file management
Command-line shell access
Graphical desktop environments and desktop applications
Web-server based applications (e.g. RStudio, Jupyter, Tensorboard)
Existing SCC Account Temporary Tutorial Account
1. Open a web browser 1. Open a web browser
2. Navigate to http://scc-ondemand.bu.edu 2. Navigate to http://scc-ondemand-2fa.bu.edu
3. Log in with your BU Kerberos Credentials 3. Log in with Tutorial Account
Click on Interactive Apps/Desktop
eclipse/2019-06
click
When your desktop is ready click Connect to Desktop
Enter this command to create a
directory in your home folder and to
copy in tutorial files:
/net/scc2/scratch/intro_to_cpp.sh
Run the Eclipse software
Part 1: Part 3:
Intro to C++ Defining C++ classes
Object oriented concepts Look at the details of how they
Write a first program work
Part 2: Part 4:
Using C++ objects Class inheritance
Standard Template Library Virtual methods
Basic debugging Available C++ tools on the
SCC
Tutorial Outline: Part 1
C++ is…
Compiled.
A separate program, the compiler, is used to turn C++ source code into a form directly
executed by the CPU.
Strongly typed and unsafe
Conversions between variable types must be made by the programmer (strong typing) but can
be circumvented when needed (unsafe)
C compatible
call C libraries directly and C code is nearly 100% valid C++ code.
Capable of very high performance
The programmer has a very large amount of control over the program execution, compilers
are high quality.
Object oriented
With support for many programming styles (procedural, functional, etc.)
No automatic memory management (mostly)
The programmer is in control of memory usage
When to choose C++
Despite its many competitors C++ has remained popular for ~30 years and will
continue to be so in the foreseeable future.
Why?
Complex problems and programs can be effectively implemented
OOP works in the real world.
About Eclipse
Started in 2001 by IBM.
The Eclipse Foundation (2004) is an independent, non-profit corporation that maintains and
promotes the Eclipse platform.
Cross-platform: supported on Mac OSX, Linux, and Windows
Supports numerous languages: C++, C, Fortran, Java, Python, and more.
Click Next.
A first program
Last screen. Don’t change anything
here, just click Finish.
A first program
Now click the Workbench button in the welcome screen to go to the newly
created project.
hello_world.cpp
has been auto-
generated.
cout is the object that writes to the stdout device, i.e. the console
window.
It is part of the C++ standard library.
Without the “using namespace std;” line this would have been called
as std::cout. It is defined in the iostream header file.
<< is the C++ insertion operator. It is used to pass characters from
the right to the object on the left.
endl is the C++ newline character.
Header Files
C++ (along with C) uses header files as to hold definitions for the compiler to use while
compiling.
A source file (file.cpp) contains the code that is compiled into an object file (file.o).
The header (file.h) is used to tell the compiler what to expect when it assembles the
program in the linking stage from the object files.
Source files and header files can refer to any number of other header files.
When compiling the linker connects all of the object (.o) files together into the
executable.
Make some changes
Let’s put the message into some variables #include <iostream>
using namespace std;
of type string and print some numbers.
Things to note: int main() {
Strings can be concatenated with a + operator. string hello = "Hello";
string world = "world!";
No messing with null terminators or strcat() as in
string msg = hello + " " +
C
world ;
Some string notes: cout << msg << endl;
Access a string character by brackets or msg[0] = 'h';
function: cout << msg << endl;
msg[0] “H” or msg.at(0) “H” return 0;
}
C++ strings are mutable – they can be
changed in place.
Re-run and check out the output.
A first C++ class: string
#include <iostream>
string is not a basic type (more using namespace std;
on those later), it is a class.
int main() {
string hello creates an string hello = "Hello";
instance of a string called hello. string world = "world!";
string msg = hello + " " +
hello is an object. It is world ;
cout << msg << endl;
initialized to contain the string msg[0] = 'h';
“Hello”. cout << msg << endl;
return 0;
A class defines some data and a }
set of functions (methods) that
operate on that data.
A first C++ class: string
int main()
Tweak the code to print the number {
string hello = "Hello" ;
of characters in the string, build, and string world = "world!" ;
run it. string msg = hello + " " + world ;
cout << msg << endl ;
msg[0] = 'h';
cout << msg << endl ;
size() is a public method, usable by
code that creates the object. cout << msg.size() << endl ;
return 0;
}
The internal tracking of the size and
the storage itself is private, visible cout prints integers
only inside the string class source without any modification!
code.
Break your code.
Fix your code so it still compiles and then we’ll move on…
Basic Syntax
C++ syntax is very similar to C, Java, or C#. Here’s a few things up front and we’ll cover
more as we go along.
Curly braces are used to denote a code block (like the main() function):
{ … some code… }
Comments are marked for a single line with a // or for multilines with a pair of /* and */ :
// this is a comment.
/* everything in here
is a comment */
void my_function() {
Variables can be declared at any time in a code block. int a ;
a=1 ;
int b;
}
Functions are sections of code that are called from other code. Functions always have a
return argument type, a function name, and then a list of arguments separated by
commas:
http://www.cplusplus.com/doc/tutorial/variables/
const float pi = 3.14 ;
Read-Only Types const string w = "Const String" ;
The const keyword can be combined with any type declaration to make
read-only variables.
The compiler will stop with an error if a const variable has a new value
assigned to it in your code.
Need to be sure of integer sizes?
In the same spirit as using integer(kind=8) type notation in Fortran, there are type definitions that
exactly specify exactly the bits used. These were added in C++11.
These can be useful if you are planning to port code across CPU architectures (ex. Intel 64-bit
CPUs to a 32-bit ARM on an embedded board) or when doing particular types of integer math.
For a full list and description see: http://www.cplusplus.com/reference/cstdint/
#include <cstdint>
Name Name Value
int8_t uint8_t 8-bit integer
int16_t uint16_t 16-bit integer
int32_t uint32_t 32-bit integer
int64_t uint64_t 64-bit integer
Reference and Pointer Variables
The object hello
occupies some
string hello = "Hello"; computer memory.
A pointer to the hello object string. hello_ptr
string *hello_ptr = &hello;
is assigned the memory address of object
string &hello_ref = hello; hello which is accessed with the “&” syntax.
Variable and object values are stored in particular locations in the computer’s memory.
Reference and pointer variables store the memory location of other variables.
Pointers are found in C. References are a C++ variation that makes pointers easier and safer to
use.
More on this topic later in the tutorial.
Type Casting
C++ is strongly typed. It will auto-convert a variable of one type to another where it can.
short x = 1 ;
int y = x ; // OK
string z = y ; // NO
double x = 1.0 ;
int y = (int) x ;
float z = (float) (x / y) ;
But when using C++ it’s best to stick with deliberate type casting using the 4 different
ways that are offered…
Type Casting double d = 1234.56 ;
float f = static_cast<float>(d) ;
// same as
float g = (float) d ;
static_cast<new type>( expression ) // same as
float h = d ;
This is exactly equivalent to the C style cast.
This identifies a cast at compile time.
This makes it clear to another programmer that you really intended a cast that
reduces precision (ex. double float) even if it would happen automatically.
~99% of all your casts in C++ will be of this type.
Takes the bits in the expression and re-uses them unconverted as a new type. Also The programmer
only works on reference or pointer type variables. must make sure
Sometimes useful when reading or writing binary files or when dealing with hardware everything is
correct!
devices like serial or USB ports.
The function arguments L and W
The return type is float. are sent as type float.
Functions float RectangleArea1(float L, float W) {
return L*W ;
Open the project “FunctionExample” in } Product is computed and returned
the Part 1 Eclipse project file.
Compile and run it!
Functions.h
Header file that declares the 4 functions.
FunctionExample.cpp
Contains the “main” routine.
Includes the Functions.h file so the 4 functions can be called.
The FunctionExample.o and Functions.o object files are linked to make the executable.
Using the Eclipse Debugger
To show how these functions work we will use the Eclipse interactive debugger to step through the program
line-by-line to follow the function calls.
Click the Debug button:
Add Breakpoints
Breakpoints tell the debugger to halt at a
particular line so that the state of the
program can be inspected.
Right-click over the line numbers, go to
Breakpoint Types and choose C/C++
Breakpoints
Double click next to the line numbers in
the functions to add breakpoints.