Introduction to C/C++ History and Basics

Introduction to C/C++
Doug Sondak
SCV
sondak@bu.edu
Outline
Goals
  
C/C++ History
Basic syntax
makefiles
Additional syntax
Information Services & Technology
2
2/25/2025
Goals
To be able to write simple C/C++ programs
To be able to understand and modify existing C/C++
code
To be able to write and use makefiles
Information Services & Technology
3
2/25/2025
Compiled vs. Interpreted Languages
Interpreted languages
when you type something, e.g., “x=y+z”, it is immediately converted
to machine language and executed
examples:  Matlab,  Python
advantage
lots off convenient features
disadvantage
can be slow and memory-intensive
Information Services & Technology
4
2/25/2025
Compiled (cont’d)
Compiled languages
examples: C,  C++,  Fortran
s
o
u
r
c
e
 
c
o
d
e
 
i
s
 
w
r
i
t
t
e
n
 
u
s
i
n
g
 
a
 
t
e
x
t
 
e
d
i
t
o
r
source code does nothing by itself – it’s just text
we will use source file suffix .cpp
s
o
u
r
c
e
 
c
o
d
e
 
m
u
s
t
 
b
e
 
p
r
o
c
e
s
s
e
d
 
t
h
r
o
u
g
h
 
a
 
c
o
m
p
i
l
e
r
translates source code into machine language
c
r
e
a
t
e
s
 
e
x
e
c
u
t
a
b
l
e
this is the code that you actually run
like .exe file in Windows
Information Services & Technology
5
2/25/2025
C History
Developed by Dennis Ritchie at Bell Labs in 1972
Originally designed for system software
Impetus was porting of Unix to a DEC PDP-11
PDP-11 had 24kB main memory!
1978 book “The C Programming Language” by
Kernighan & Ritchie served as standard
Official ANSI standard published in 1989
Updated in 1999
Information Services & Technology
6
2/25/2025
C++ History
C++ was developed by Bjarne Stroustrup at Bell Labs
in 1979
implemented object-oriented features of another
language, “Simula,” in C
originally called “C with Classes”
name changed to C++ in 1983
first commercial compiler in 1985
official standard published in 1988
Information Services & Technology
7
2/25/2025
C vs. C++
C is essentially a subset of C++
There are some “convenience features” in C++ that we
will utilize here
Since we will be writing rudimentary codes, we will not get into
object-oriented C++ constructs
We will use the GNU C++ compiler g++
Information Services & Technology
8
2/25/2025
Types of Variables
e
a
c
h
 
v
a
r
i
a
b
l
e
 
a
n
d
 
v
a
l
u
e
 
h
a
s
 
a
 
t
y
p
e
some common types
int
short for “integer”
number with no decimal places
1,   857436
float
short for “floating-point”
number with decimal places
1.234,  4.0
Information Services & Technology
9
2/25/2025
Types of Variables (cont’d)
char
short for “character”
enclosed in 
single
 quotes
‘x’,   ‘$’
character string
 is string of chars enclosed in 
double
 quotes
“This is a character string.”
Information Services & Technology
10
10
2/25/2025
C/C++ Syntax
Case-sensitive
Spaces don’t matter except within character strings
I use them liberally to make code easy to read
Source lines end with semicolons (as in Matlab)
Comments
notes for humans that are ignored by the compiler
C:  enclosed by 
/*  */
C++:   
//
 at beginning of comment
many C compilers also accept this syntax
Use them liberally!
IS&T Organization
11
11
2/25/2025
C/C++ Syntax (cont’d)
s
o
u
r
c
e
 
c
o
d
e
 
c
o
n
t
a
i
n
s
 
f
u
n
c
t
i
o
n
s
each one performs some task
you write some of them
some are intrinsic to the language
e
v
e
r
y
 
c
o
d
e
 
c
o
n
t
a
i
n
s
 
a
t
 
l
e
a
s
t
 
o
n
e
 
f
u
n
c
t
i
o
n
,
 
c
a
l
l
e
d
 
m
a
i
n
functions often, though not always, return a value
f
u
n
c
t
i
o
n
 
i
s
 
c
h
a
r
a
c
t
e
r
i
z
e
d
 
b
y
 
t
h
e
 
t
y
p
e
 
o
f
 
v
a
l
u
e
 
i
t
 
r
e
t
u
r
n
s
int, float, char, etc.
if function does not return anything, we will declare (characterize)
it as an “int” function
IS&T Organization
12
12
2/25/2025
C/C++ Syntax (3)
functions may, but do not have to, take arguments
“arguments” are input values to the function
code blocks, including entire functions, are enclosed
within “curly braces” {  }
main function is defined in source code as follows:
int main( ) {
   
function statements
}
Information Services & Technology
13
13
2/25/2025
type declaration
function name
         function arguments
 (we have no arguments here
   but still need parentheses)
C/C++  Syntax (4)
Style note: some people like to arrange the brackets
like
int main( )
{
    
function statements
}
Either way is fine
Be consistent!
Information Services & Technology
14
14
2/25/2025
C/C++  Syntax (5)
cout 
is a 
stream 
that is used to direct output to the
screen, e.g.
cout  <<  “my string”;
sends the string to cout, i.e., to the screen
The above syntax does not include a carriage return at
the end of the line.  We can add the carriage return
with:
cout  <<  “my string” << endl;
Information Services & Technology
15
15
2/25/2025
C/C++  Syntax (6)
s
o
m
e
 
p
r
o
g
r
a
m
 
e
l
e
m
e
n
t
s
 
(
b
u
i
l
t
-
i
n
 
f
u
n
c
t
i
o
n
s
,
 
v
a
r
i
a
b
l
e
s
,
e
t
c
.
)
 
a
r
e
 
c
o
n
t
a
i
n
e
d
 
i
n
 
h
e
a
d
e
r
 
f
i
l
e
s
to use these program elements you need to “include”
the appropriate header files in your source code
in C, header files have .h suffixes
may or may not have .h suffix in C++
syntax for inclusion of header files:
#include <
header_file_name
>
Included 
before
 function definition
<
  and  
>
  are part of the syntax
N
o
t
e
 
t
h
a
t
 
t
h
e
 
#
i
n
c
l
u
d
e
 
s
t
a
t
e
m
e
n
t
 
d
o
e
s
 
n
o
t
 
e
n
d
 
w
i
t
h
 
a
 
;
Information Services & Technology
16
16
2/25/2025
C/C++  Syntax (7)
C++ (but not C) has a feature, 
namespace
, that
defines packages of functions, etc.
This is fairly new, and you might not see it in older C++ programs
The 
cout
 stream is defined in the 
iostream 
header file,
which is part of the “std” 
namespace
The syntax to use the std namespace is
using namespace std;
Information Services & Technology
17
17
2/25/2025
Exercise 1
Write a “hello world” program in an editor
Program should print a character string
General structure of code, in order:
include the file “iostream”
not iostream.h, just “iostream”
use the “std” namespace
define main function
use cout and endl to print string to screen
Save it to the file name hello.cpp
solution
Information Services & Technology
18
18
2/25/2025
Compilation
A compiler is a program that reads source code and
converts it to a form usable by the computer
Code compiled for a given type of processor will not
generally run on other types
AMD and Intel are compatible
We’ll use g++, since it’s free and readily available
Information Services & Technology
19
19
2/25/2025
Compilation (cont’d)
Compilers have numerous options
See gcc compiler documentation at
http://gcc.gnu.org/onlinedocs/
gcc refers to the “GNU compiler collection,” which includes the C
compiler (gcc) and the C++ compiler (g++)
For now, we will simply use the 
–o
 option, which
allows you to specify the name of the resulting
executable
Information Services & Technology
20
20
2/25/2025
Compilation (3)
In a Unix window:
g++  –o  hello  hello.cpp
“hello” is name of executable file (compiler output)
“hello.cpp” is source file name (compiler input)
Compile your code
If it simply returns a Unix prompt it worked
If you get error messages, read them carefully and see
if you can fix the source code and re-compile
Information Services & Technology
21
21
2/25/2025
Compilation (4)
Once it compiles correctly, type
hello
at the Unix prompt, and it will run the program
should print the string to the screen
Information Services & Technology
22
22
2/25/2025
Declarations
different variable types (int, float, etc.) are represented
differently internally
different bit patterns
must tell compiler the type of every variable by
declaring
 them
example declarations:
int  i,  jmax,  k_value;
float  xval,  elapsed_time;
char  aletter, bletter;
Information Services & Technology
23
23
2/25/2025
Arithmetic
+,  -,  *,  /
No power operator (see next bullet)
Math functions in math.h
pow(x,y) raises x to the y power
sin,  acos,  tanh,  exp,  sqrt,  etc.
for some compilers, need to add  
–lm  
flag to compile command to
access math library
Exponential notation indicated by letter “e”
                          
4.2e3
Good
 
practice to use decimal points with floats, e.g.,
     x = 1.0   rather than   x = 1
Information Services & Technology
24
24
2/25/2025
Arithmetic (cont’d)
++
 and 
--
 operators
these are equivalent:
i = i+1;
i++;
always increments/decrements by 1
+=
these are equivalent:
x = x + 46.3*y;
x += 46.3*y;
Information Services & Technology
25
25
2/25/2025
Arithmetic (3)
Can convert types with 
cast
 operator
float xval;
int i, j;
xval = (float) i / (float) j;
Pure integer arithmetic 
truncates
 result!
5/2 = 2
2/5 = 0
Information Services & Technology
26
26
2/25/2025
Exercise 2
Write program to convert a Celcius temperature to
Fahrenheit and print the result.
Hard-wire the Celcius value to 100.0
We’ll make it an input value in a subsequent exercise
Don’t forget to declare all variables
     
F = (9/5)C + 32
solution
Information Services & Technology
27
27
2/25/2025
cin
cin 
reads input from the screen
cin  >>  
var
;
Note:  
>>
 rather than 
<<
 as with cout
Writes input value to variable 
var
Often use cout and cin to prompt for a value:
cout  <<  “Enter value:  ”;
cin  >> x;
Information Services & Technology
28
28
2/25/2025
Exercise 3
Modify Celcius program to read value from keyboard
Prompt for Celcius value using cout
Read value using cin
Rest can remain the same as last exercise
solution
Information Services & Technology
29
29
2/25/2025
Arrays
Can declare arrays using [ ]
float  x[100];
char  a[25];
Array indices start at 
zero
Declaration of x above creates locations for x[0] through x[99]
Multiple-dimension arrays are declared as follows:
int  a[10][20];
Information Services & Technology
30
30
2/25/2025
Arrays (cont’d)
Character strings (char arrays) always end with the
character 
\0
You usually don’t have to worry about it as long as you dimension
the string 1 larger than the length of the required string
char name[5];
name = “Fred”;
char name[4];
name = “Fred”;
Information Services & Technology
31
31
2/25/2025
works
doesn’t work
For Loop
for
 loop repeats calculation over range of indices
for(i=0;  i<n;  i++){
      a[i] = sqrt( pow(b[i],2)  +  pow(c[i],2)  );
}
for
 statement has 3 parts:
initialization
completion condition
what to do after each iteration
Information Services & Technology
32
32
2/25/2025
Exercise 4
Write program to:
declare two vectors of length 3
prompt for vector values
calculate dot product
print the result
solution
Information Services & Technology
33
33
2/25/2025
Pointers
Memory is organized in units of 
words
Word size is architecture-dependent
Pentium: 4 bytes
Xeon, Itanium: 8 bytes
Each word has a numerical address
Information Services & Technology
34
34
2/25/2025
0
8
16
32
Pointers (cont’d)
When you 
declare
 a variable, a location of appropriate
size is reserved in memory
When you set its value, the value is placed in that
memory location
Information Services & Technology
35
35
2/25/2025
float  x;
x = 3.2;
0
8
16
32
address
    
3.2
Pointers (3)
A pointer is a variable containing a memory 
address
Declared using * prefix
float *p;
Address operator 
&
Address of specified variable
float x, *p;
p = &x;
Information Services & Technology
36
36
2/25/2025
Pointers (4)
float x, *p;
p = &x;
Information Services & Technology
37
37
2/25/2025
 
 
1040
1048
1052
1056
address
0
8
16
32
address
p
16
Pointers (5)
Depending on context, * can also be the 
dereferencing
operator
Value stored in memory location pointed to by specified pointer
*p = 3.2;
Common newbie error
float *p;
*p = 3.2;
float x, *p;
p = &x;
*p = 3.2;
Information Services & Technology
2/25/2025
W
r
o
n
g
!
 
 
p
 
d
o
e
s
n
t
 
h
a
v
e
 
v
a
l
u
e
 
y
e
t
correct
Pointers (6)
The name of an array is actually a pointer to the
memory location of the first element
a[100]
“a” is a pointer to the first element of the array (a[0])
These are equivalent:
x[0] = 4.53;
*x = 4.53;
Information Services & Technology
39
39
2/25/2025
Pointers (7)
If p is a pointer and n is an integer, the syntax 
p+n
means to advance the pointer by n 
memory locations
These are therefore equivalent:
x[4] = 4.53;
*(x+4) = 4.53;
Information Services & Technology
40
40
2/25/2025
Pointers (8)
Information Services & Technology
41
41
2/25/2025
In multi-dimensional arrays, values are stored in
memory with 
last 
index varying most rapidly (a[0][0],
a[0][1], … )
Opposite of Matlab and Fortran
The two statements in each box are equivalent for an
array declared as int a[20][20]:
a[0][17] = 1;                    a[1][0] = 5;
*(a+17) = 1;                     *(a+20) = 5;
sizeof
Information Services & Technology
42
42
2/25/2025
Some functions require size of something in bytes
A useful function – sizeof(
arg
)
The argument 
arg
 can be a variable, an array name, a type
Returns no. bytes in arg
float x, y[5];
sizeof(x)
  
(  4)
sizeof(y)
  
(20)
sizeof(float)
  
(  4)
Dynamic Allocation
Suppose you need an array, but you don’t know how
big it needs to be until run time.
Use 
malloc
 function
malloc(
n
)
n is no. 
bytes
 to be allocated
returns pointer to allocated space
lives in stdlib.h
Information Services & Technology
43
43
2/25/2025
Dynamic Allocation (cont’d)
Information Services & Technology
44
44
2/25/2025
Declare pointer of required type
float *myarray;
Suppose we need 101 elements in array
malloc requires no. bytes, cast as appropriate pointer
myarray = (float *) malloc(101*sizeof(float));
free 
releases space when it’s no longer needed:
free(myarray);
Exercise 5
Modify dot-product program to handle vectors of any
length
Prompt for length of vectors
Read length of vectors from screen
Dynamically allocate vectors
Don’t forget to include stdlib.h so you have access to the malloc
function
solution
Information Services & Technology
45
45
2/25/2025
if/else if/else
Information Services & Technology
46
46
2/25/2025
Conditional execution of block of source code
Based on relational operators
 
<
  
less than
 
>
  
greater than
 
==
 
equal
 
<=
 
less than or equal
 
>=
 
greater than or equal
 
!=
 
not equal
 
&&         
 
and
 
||           
 
or
if/else if/else (cont’d)
Information Services & Technology
47
47
2/25/2025
if( x > 0.0  && y > 0.0 ){
    z = 1.0/(x+y);
}else if( x < 0.0  &&   y < 0.0){
    z = -1.0/(x+y);
}else{
    printf(“Error condition\n”);
}
if/else if/else (3)
Can use “if” without “else”
if( x > 0.0  && y > 0.0 ){
     printf(“x and y are both positive\n”);
}
Information Services & Technology
48
48
2/25/2025
Exercise 6
Information Services & Technology
49
49
2/25/2025
In dot product code, check if the magnitude of the dot
product is less than         using the absolute value
function 
fabsf
.  If it is, print a warning message.
With some compilers you would need to include math.h for the fabsf
function
With some compilers you would need to link to the math library by
adding the flag –lm to the end of your compile/link command
solution
Functions
Information Services & Technology
50
50
2/25/2025
Function returns a single item (number, array, etc.)
Return type must be declared
Argument types must be declared
Sample function 
definition
:
float sumsqr(float x, float y){
    float z;
    z = x*x + y*y;
    return z;
}
Functions (cont’d)
Information Services & Technology
51
51
2/25/2025
Use of sumsqr function:
a = sumsqr(b,c);
Call by 
value
when function is called, copies are made of the arguments
scope of copies is scope of function
after return from function, copies no longer exist
Functions (3)
Information Services & Technology
52
52
2/25/2025
b = 2.0;  c = 3.0;
a = sumsqr(b, c);
cout << b;
float sumsqr(float x, float y){
    float z;
    z = x*x + y*y;
 
 
 
 
x
 
=
 
1
9
3
8
.
6
;
    return z;
}
t
h
i
s
 
l
i
n
e
 
d
o
e
s
 
n
o
t
h
i
n
g
!
w
i
l
l
 
p
r
i
n
t
 
2
.
0
Functions (4)
If you want to change argument values, pass pointers
int swap(int *i,  int *j){
     int k;
     k = *i;
     *i = *j;
     *j = k;
     return 0;
}
Information Services & Technology
53
53
2/25/2025
Functions (5)
Let’s examine the following code fragment:
int a, b;
a = 2;  b = 3;
swap(&a, &b);
Memory after setting values of a and b
Information Services & Technology
54
54
2/25/2025
address
16
20
24
28
variable
b
a
3
2
Functions (6)
When function is called, copies of arguments are
created in memory
i, j are pointers to ints with values &a and &b
Information Services & Technology
55
55
2/25/2025
address
16
20
24
28
variable
b
a
3
2
address
48
52
56
60
variable
j
i
24
20
&a
i
&b
j
swap(&a, &b);
int swap(int *i,  int *j){  ...  }
Information Services & Technology
56
56
2/25/2025
Functions (7)
What happens to memory for each line in the function?
k
address
16
20
24
28
variable
b
a
3
2
address
48
52
56
60
variable
j
i
24
20
int k;
address
16
20
24
28
variable
b
a
3
2
address
48
52
56
60
variable
j
i
24
20
k = *i;
k
2
Information Services & Technology
57
57
2/25/2025
Functions (8)
 
k
address
16
20
24
28
variable
b
a
3
3
address
48
52
56
60
variable
j
i
24
20
*i = *j;
*j = k;
k
2
2
Information Services & Technology
58
58
2/25/2025
Functions (9)
                                       return 0;
address
48
52
56
60
variable
24
20
2
Exercise 7
Modify dot-product program to use a function to
compute the dot product
The function definition should go 
before
 the main program in the
source file
Arguments can be an integer containing the length of the vectors and
a pointer to each vector
Do not give function same name as executable
I called my executable “dotprod” and the function “dp”
solution
Information Services & Technology
59
59
2/25/2025
Function Prototypes
C compiler checks arguments in function definition and
calls
number
type
If definition and call are in different 
files
, compiler
needs more information to perform checks
this is done through 
function prototypes
Information Services & Technology
60
60
2/25/2025
Function Prototypes (cont’d)
Prototype looks like 1
st
 line of function definition
type
name
argument types
float dp(int n,  float *x,  float *y);
Argument names are optional:
float dp(int,  float*,  float*);
Information Services & Technology
61
61
2/25/2025
Function Prototypes (3)
Prototypes are often contained in include files
#include “mycode.h”   // contains prototype for myfunc
int main(){
myfunc(x);
}
Information Services & Technology
62
62
2/25/2025
Basics of Code Management
Large codes usually consist of multiple files
I create a separate file for each function
Easier to edit
Can recompile one function at a time
Files can be compiled, but not linked, using –c option;
then object files can be linked later
g++  –c  mycode.cpp
g++  –c  myfunc.cpp
g++  –o  mycode  mycode.o  myfunc.o
Information Services & Technology
63
63
2/25/2025
Exercise 8
Put dot-product function and main program in separate
files
Create header file
function prototype
.h suffix
include at top of file containing main
Compile, link, and run
solution
Information Services & Technology
64
64
2/25/2025
Makefiles
Make is a Unix utility to help manage codes
When you make changes to files, it will
automatically deduce which files have been modified and compile
them
link latest object files
Makefile 
is a file that tells the 
make
 utility what to do
Default name of file is “makefile” or “Makefile”
Can use other names if you’d like
Information Services & Technology
65
65
2/25/2025
Makefiles (cont’d)
Makefile contains different sections with different
functions
The sections are 
not
 executed in order!
Comment character is 
#
As with source code, use comments freely
Information Services & Technology
66
66
2/25/2025
Makefiles (3)
Simple sample makefile
### suffix rule
.SUFFIXES:
.SUFFIXES: .cpp .o
.cpp.o:
  
  g++  -c   $*.cpp
### compile and link
myexe:  mymain.o   fun1.o   fun2.o   fun3.o
  
  g++   –o    myexe   mymain.o   fun1.o   fun2.o   fun3.o
Information Services & Technology
67
67
2/25/2025
Makefiles (4)
Have to define all file suffixes that may be
encountered
.SUFFIXES:  .o  .cpp
Just to be safe, delete any default suffixes first with a
null  
.SUFFIXES:  
command
.SUFFIXES:
.SUFFIXES:  .o  .cpp
Information Services & Technology
68
68
2/25/2025
Makefiles (5)
Have to tell how to create one file suffix from another
with a 
suffix rule
.cpp.o:
   
g++  -c  $*.cpp
The first line indicates that the rule tells how to create
a .o file from a .cpp file
The second line tells 
how
 to create the .o file
*$ is automatically the root of the file name
The big space before g++ is a tab, and you must use
it!
Information Services & Technology
69
69
2/25/2025
Makefiles (6)
Finally, everything falls together with the definition of a
rule
target:  prerequisites
   
recipe
The target is any name you choose
Often use name of executable
Prerequisites are files that are required by other files
e.g., executable requires object files
Recipe tells what you want the makefile to do
May have multiple targets in a makefile
Information Services & Technology
70
70
2/25/2025
Makefiles (7)
Revisit sample makefile
### suffix rule
.SUFFIXES:
.SUFFIXES: .cpp .o
.cpp.o:
  
  g++  -c   $*.cpp
### compile and link
myexe:  mymain.o   fun1.o   fun2.o   fun3.o
  
  g++   –o    myexe   mymain.o   fun1.o   fun2.o   fun3.o
Information Services & Technology
71
71
2/25/2025
automatic variable for file root
Makefiles (8)
When you type “make,” it will look for a file called
“makefile” or “Makefile”
searches for the first target in the file
In our example (and the usual case) the object files
are prerequisites
checks suffix rule to see how to create an object file
In our case, it sees that .o files depend on .cpp files
checks time stamps on the associated .o and .cpp files
to see if the .cpp is newer
If the .cpp file is newer it performs the suffix rule
In our case, compiles the routine
Information Services & Technology
72
72
2/25/2025
Makefiles (9)
Once all the prerequisites are updated as required, it
performs the recipe
In our case it links the object files and creates our
executable
Many makefiles have an additional target, “clean,” that
removes .o and other files
clean:
   
rm  –f  *.o
When there are multiple targets, specify desired target
as argument to make command
make clean
Information Services & Technology
73
73
2/25/2025
Makefiles (10)
Also may want to set up dependencies for header files
When header file is changed, files that include it will automatically
recompile
example:
myfunction.o:  myincludefile.h
if time stamp on .h file is newer than .o file and .o file is required in
another dependency, will recompile myfunction.cpp
no recipe is required
Information Services & Technology
74
74
2/25/2025
Exercise 9a
Create a makefile for your dot product code
Include 2 targets
create executable
clean
Include header dependency (see previous slide)
Delete old object files and executable manually
r
m
 
 
*
.
o
 
 
d
o
t
p
r
o
d
Build your code using the makefile
solution
Information Services & Technology
75
75
2/25/2025
Exercise 9b
T
y
p
e
 
m
a
k
e
 
a
g
a
i
n
should get message that it’s already up to date
C
l
e
a
n
 
f
i
l
e
s
 
b
y
 
t
y
p
i
n
g
 
m
a
k
e
 
c
l
e
a
n
T
y
p
e
 
l
s
 
t
o
 
m
a
k
e
 
s
u
r
e
 
f
i
l
e
s
 
a
r
e
 
g
o
n
e
T
y
p
e
 
m
a
k
e
 
a
g
a
i
n
will rebuild code
Update time stamp on header file
t
o
u
c
h
 
 
d
o
t
p
r
o
d
.
h
T
y
p
e
 
m
a
k
e
 
a
g
a
i
n
should recompile main program, but not dot product function
Information Services & Technology
76
76
2/25/2025
C Preprocessor
Initial processing phase before compilation
Directives start with 
#
We’ve seen one directive already, 
#include
simply includes specified file in place of directive
Another common directive is 
#define
#define 
NAME text
NAME
 is any name you want to use
text 
is the text that replaces 
NAME 
wherever it appears in source
code
Information Services & Technology
77
77
2/25/2025
C Preprocessor (cont’d)
#define often used to define global constants
#define NX   51
#define NY 201
float x[NX][NY];
Also handy to specify precision
#define REAL double
REAL x, y;
Information Services & Technology
78
78
2/25/2025
C Preprocessor (3)
Since #define is often placed in header file, and
header will be included in multiple files, this construct
is commonly used:
#ifndef REAL
#define REAL double
#endif
This basically says “If REAL is not defined, go ahead
and define it.”
Information Services & Technology
79
79
2/25/2025
C Preprocessor (4)
Can also check values using the 
#if 
directive
In the current exercise code, the function 
fabsf
 is used,
but that is for floats.  For doubles, the function is 
fabs
.
We can add this to out .h file:
#if REAL == double
#define ABS fabs
#else
#define ABS fabsf
#endif
Information Services & Technology
80
80
2/25/2025
C Preprocessor (5)
#define can also be used to define a macro with
substitutable arguments
#define  ind(m,n)   (n + NY*m)
k = 5*ind(i,j);               
k = 5*(i + NY*j);
Be careful to use ( ) when required!
without ( ) above example would come out wrong
                                       
k = 5*i + NY*j      
wrong!
Information Services & Technology
81
81
2/25/2025
Exercise 10
Modify dot-product code to use preprocessor
directives to declare double-precision floats
Add directives to header file to define 
REAL
 as shown in “C
Preprocessor (3)”
Add directives to header file to choose 
ABS
 as shown in “C
Preprocessor (4)”
Change “
fabsf
” to “
ABS
” in main routine
Include math.h in main program
Add header to function (for definition of REAL)
Don’t forget to modify all occurrences of “float” to “REAL” in dot.cpp
and dotprod.cpp
solution
Information Services & Technology
82
82
2/25/2025
Structures
Can package a number of variables under one name
struct grid{
   int nvals;
   float
 x[100][100], y[100][100], jacobian[100][100];
};
Note semicolon at end of definition
Information Services & Technology
83
83
2/25/2025
Structures (cont’d)
To declare a variable as a struct
struct  grid  mygrid1;
Components are accessed using 
.
mygrid1.nvals = 20;
mygrid1.x[0][0] = 0.0;
Handy way to transfer lots of data to a function
int  calc_jacobian(struct  grid  mygrid1){…
Information Services & Technology
84
84
2/25/2025
Exercise 11
Define struct 
rvec 
with 2 components in your header
file (.h)
vector length (int)
pointer to REAL vector
Modify dot-product code to use 
rvec
 structure
solution
Information Services & Technology
85
85
2/25/2025
i/o
Often need to read/write data from/to files rather than
screen
File is associated with a 
file pointer 
through a call to
the 
fopen
 function
File pointer is of type 
FILE
, which is defined in
 <iostream>   for C++ with std namespace
 <stdio.h> for C
Information Services & Technology
86
86
2/25/2025
i/o (cont’d)
fopen takes 2 character-string arguments
file name
mode
“r”
 
read
“w”
 
write
“a”
 
append
FILE *fp;
fp = fopen(“myfile.d”, “w”);
Information Services & Technology
87
87
2/25/2025
i/o (3)
Write to file using 
fprintf
Need stdio.h
fprintf  
has 3 arguments
1.
File pointer
2.
Character string containing what to print, including any formats
%f  for float or double
%d for int
%s for character string
3.
Variable list corresponding to formats
Information Services & Technology
88
88
2/25/2025
i/o (4)
Special character 
\n
 produces new line (carriage
return & line feed)
Often used in character strings
“This is my character string.\n”
Example:
fprintf(fp,  “x = %f\n”,  x);
Read from file using 
fscanf
arguments same as fprintf
When finished accessing file, close it
fclose(fp);
Information Services & Technology
89
89
2/25/2025
Exercise 12
Modify  dot-product code to write the dot-product result
to a file
If magnitude is small, still write message to screen
rather than file
After result is written to file, write message  “Output
written to file” to screen.
solution
Information Services & Technology
90
90
2/25/2025
Binary i/o
Binary data require 
much
 less disk space than ascii
(formatted) data
Use “b” suffix on mode
fp = fopen(“myfile.d”, “wb”);
Use 
fwrite
, 
fread
 functions
float x[100];
fwrite( x,    sizeof(float),    100,     fp )
Note that there is no format specification
We’re strictly writing data
Information Services & Technology
91
91
2/25/2025
pointer to
1
st
 element
no. bytes in
each element
max.
 no. of
elements
file pointer
Exercise 13
Modify dot-product program to:
Write result to binary file
just write value, not character string
After file is closed, open it back up and read and print result to make
sure that it wrote/read correctly
solution
Information Services & Technology
92
92
2/25/2025
Command-Line Arguments
It’s often convenient to type some inputs on the
command line along with the executable name, e.g.,
mycode   41.3  “myfile.d”
Define 
main
 with two arguments:
1.
argc is the number of items on the command line, including name
of executable
“argument count”
2.
argv is an array of character strings containing the arguments
“argument values”
   
int main(int argc,  char *argv[ ])
Information Services & Technology
93
93
2/25/2025
Command-Line Arguments (cont’d)
Arguments are character strings, often want to convert
them to numbers
Some handy functions:
atoi converts string to integer
atof converts string to double
To convert to float, recast result of atof
They live in stdlib.h
Information Services & Technology
94
94
2/25/2025
Exercise 14
Convert dot-product code to take arguments on
command line rather than prompt for them
Arguments will be:
Size of vectors
Values of first vector
Values of second vector
Use atoi and atof
Cast doubles to “REAL”
If you get a segmentation fault when you run, you may
have forgotten command-line arguments
solution
Information Services & Technology
95
95
2/25/2025
References
Lots of books available
I like Kernighan & Ritchie, “The C Programming Language”
Good C++ book for scientists:
Barton and Nackman, “Scientific and Engineering C++”
Quick and dirty C++ book:
Liberty, “Teach Yourself C++ in 21 Days”
gcc/g++
http://gcc.gnu.org/onlinedocs/gcc-4.5.1/gcc/
Information Services & Technology
96
96
2/25/2025
Survey
Please fill out the course survey at
http://scv.bu.edu/survey/spring11tut_survey.html
Information Services & Technology
97
97
2/25/2025
Slide Note
Embed
Share

This material covers the history, syntax, and basics of C/C++. Learn about compiled vs. interpreted languages, the development of C and C++, and essential concepts for writing and understanding programs. Gain insights into compiled languages like C and C++, their significance, and more.

  • C/C++
  • Programming
  • History
  • Basics
  • Compiled Languages

Uploaded on Feb 25, 2025 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. Introduction to C/C++ Doug Sondak SCV sondak@bu.edu

  2. Information Services & Technology 2/25/2025 Outline Goals C/C++ History Basic syntax makefiles Additional syntax 2

  3. Information Services & Technology 2/25/2025 Goals To be able to write simple C/C++ programs To be able to understand and modify existing C/C++ code To be able to write and use makefiles 3

  4. Information Services & Technology 2/25/2025 Compiled vs. Interpreted Languages Interpreted languages when you type something, e.g., x=y+z , it is immediately converted to machine language and executed examples: Matlab, Python advantage lots off convenient features disadvantage can be slow and memory-intensive 4

  5. Information Services & Technology 2/25/2025 Compiled (cont d) Compiled languages examples: C, C++, Fortran source code is written using a text editor source code does nothing by itself it s just text we will use source file suffix .cpp source code must be processed through a compiler translates source code into machine language creates executable this is the code that you actually run like .exe file in Windows 5

  6. Information Services & Technology 2/25/2025 C History Developed by Dennis Ritchie at Bell Labs in 1972 Originally designed for system software Impetus was porting of Unix to a DEC PDP-11 PDP-11 had 24kB main memory! 1978 book The C Programming Language by Kernighan & Ritchie served as standard Official ANSI standard published in 1989 Updated in 1999 6

  7. Information Services & Technology 2/25/2025 C++ History C++ was developed by Bjarne Stroustrup at Bell Labs in 1979 implemented object-oriented features of another language, Simula, in C originally called C with Classes name changed to C++ in 1983 first commercial compiler in 1985 official standard published in 1988 7

  8. Information Services & Technology 2/25/2025 C vs. C++ C is essentially a subset of C++ There are some convenience features in C++ that we will utilize here Since we will be writing rudimentary codes, we will not get into object-oriented C++ constructs We will use the GNU C++ compiler g++ 8

  9. Information Services & Technology 2/25/2025 Types of Variables each variable and value has a type some common types int short for integer number with no decimal places 1, 857436 float short for floating-point number with decimal places 1.234, 4.0 9

  10. Information Services & Technology 2/25/2025 Types of Variables (cont d) char short for character enclosed in single quotes x , $ character string is string of chars enclosed in double quotes This is a character string. 10

  11. IS&T Organization 2/25/2025 C/C++ Syntax Case-sensitive Spaces don t matter except within character strings I use them liberally to make code easy to read Source lines end with semicolons (as in Matlab) Comments notes for humans that are ignored by the compiler C: enclosed by /* */ C++: // at beginning of comment many C compilers also accept this syntax Use them liberally! 11

  12. IS&T Organization 2/25/2025 C/C++ Syntax (cont d) source code contains functions each one performs some task you write some of them some are intrinsic to the language every code contains at least one function, called main functions often, though not always, return a value function is characterized by the type of value it returns int, float, char, etc. if function does not return anything, we will declare (characterize) it as an int function 12

  13. Information Services & Technology 2/25/2025 C/C++ Syntax (3) functions may, but do not have to, take arguments arguments are input values to the function code blocks, including entire functions, are enclosed within curly braces { } main function is defined in source code as follows: type declaration function name (we have no arguments here but still need parentheses) function arguments int main( ) { function statements } 13

  14. Information Services & Technology 2/25/2025 C/C++ Syntax (4) Style note: some people like to arrange the brackets like int main( ) { function statements } Either way is fine Be consistent! 14

  15. Information Services & Technology 2/25/2025 C/C++ Syntax (5) cout is a stream that is used to direct output to the screen, e.g. cout << my string ; sends the string to cout, i.e., to the screen The above syntax does not include a carriage return at the end of the line. We can add the carriage return with: cout << my string << endl; 15

  16. Information Services & Technology 2/25/2025 C/C++ Syntax (6) some program elements (built-in functions, variables, etc.) are contained in header files to use these program elements you need to include the appropriate header files in your source code in C, header files have .h suffixes may or may not have .h suffix in C++ syntax for inclusion of header files: #include <header_file_name> Included before function definition < and > are part of the syntax Note that the #include statement does not end with a ; 16

  17. Information Services & Technology 2/25/2025 C/C++ Syntax (7) C++ (but not C) has a feature, namespace, that defines packages of functions, etc. This is fairly new, and you might not see it in older C++ programs The cout stream is defined in the iostream header file, which is part of the std namespace The syntax to use the std namespace is using namespace std; 17

  18. Information Services & Technology 2/25/2025 Exercise 1 Write a hello world program in an editor Program should print a character string General structure of code, in order: include the file iostream not iostream.h, just iostream use the std namespace define main function use cout and endl to print string to screen Save it to the file name hello.cpp solution 18

  19. Information Services & Technology 2/25/2025 Compilation A compiler is a program that reads source code and converts it to a form usable by the computer Code compiled for a given type of processor will not generally run on other types AMD and Intel are compatible We ll use g++, since it s free and readily available 19

  20. Information Services & Technology 2/25/2025 Compilation (cont d) Compilers have numerous options See gcc compiler documentation at http://gcc.gnu.org/onlinedocs/ gcc refers to the GNU compiler collection, which includes the C compiler (gcc) and the C++ compiler (g++) For now, we will simply use the o option, which allows you to specify the name of the resulting executable 20

  21. Information Services & Technology 2/25/2025 Compilation (3) In a Unix window: g++ o hello hello.cpp hello is name of executable file (compiler output) hello.cpp is source file name (compiler input) Compile your code If it simply returns a Unix prompt it worked If you get error messages, read them carefully and see if you can fix the source code and re-compile 21

  22. Information Services & Technology 2/25/2025 Compilation (4) Once it compiles correctly, type hello at the Unix prompt, and it will run the program should print the string to the screen 22

  23. Information Services & Technology 2/25/2025 Declarations different variable types (int, float, etc.) are represented differently internally different bit patterns must tell compiler the type of every variable by declaring them example declarations: int i, jmax, k_value; float xval, elapsed_time; char aletter, bletter; 23

  24. Information Services & Technology 2/25/2025 Arithmetic +, -, *, / No power operator (see next bullet) Math functions in math.h pow(x,y) raises x to the y power sin, acos, tanh, exp, sqrt, etc. for some compilers, need to add lm flag to compile command to access math library Exponential notation indicated by letter e 4.2e3 Goodpractice to use decimal points with floats, e.g., x = 1.0 rather than x = 1 2 . 4 3 10 24

  25. Information Services & Technology 2/25/2025 Arithmetic (cont d) ++ and -- operators these are equivalent: i = i+1; i++; always increments/decrements by 1 += these are equivalent: x = x + 46.3*y; x += 46.3*y; 25

  26. Information Services & Technology 2/25/2025 Arithmetic (3) Can convert types with cast operator float xval; int i, j; xval = (float) i / (float) j; Pure integer arithmetic truncates result! 5/2 = 2 2/5 = 0 26

  27. Information Services & Technology 2/25/2025 Exercise 2 Write program to convert a Celcius temperature to Fahrenheit and print the result. Hard-wire the Celcius value to 100.0 We ll make it an input value in a subsequent exercise Don t forget to declare all variables F = (9/5)C + 32 solution 27

  28. Information Services & Technology 2/25/2025 cin cin reads input from the screen cin >> var; Note: >> rather than << as with cout Writes input value to variable var Often use cout and cin to prompt for a value: cout << Enter value: ; cin >> x; 28

  29. Information Services & Technology 2/25/2025 Exercise 3 Modify Celcius program to read value from keyboard Prompt for Celcius value using cout Read value using cin Rest can remain the same as last exercise solution 29

  30. Information Services & Technology 2/25/2025 Arrays Can declare arrays using [ ] float x[100]; char a[25]; Array indices start at zero Declaration of x above creates locations for x[0] through x[99] Multiple-dimension arrays are declared as follows: int a[10][20]; 30

  31. Information Services & Technology 2/25/2025 Arrays (cont d) Character strings (char arrays) always end with the character \0 You usually don t have to worry about it as long as you dimension the string 1 larger than the length of the required string char name[5]; name = Fred ; works char name[4]; name = Fred ; doesn t work 31

  32. Information Services & Technology 2/25/2025 For Loop for loop repeats calculation over range of indices for(i=0; i<n; i++){ a[i] = sqrt( pow(b[i],2) + pow(c[i],2) ); } for statement has 3 parts: initialization completion condition what to do after each iteration 32

  33. Information Services & Technology 2/25/2025 Exercise 4 Write program to: declare two vectors of length 3 prompt for vector values calculate dot product print the result solution n = c a b i i =1 i 33

  34. Information Services & Technology 2/25/2025 Pointers Memory is organized in units of words Word size is architecture-dependent Pentium: 4 bytes Xeon, Itanium: 8 bytes Each word has a numerical address 32 16 8 0 34

  35. Information Services & Technology 2/25/2025 Pointers (cont d) When you declare a variable, a location of appropriate size is reserved in memory When you set its value, the value is placed in that memory location float x; x = 3.2; 32 16 3.2 8 0 address 35

  36. Information Services & Technology 2/25/2025 Pointers (3) A pointer is a variable containing a memory address Declared using * prefix float *p; Address operator & Address of specified variable float x, *p; p = &x; 36

  37. Information Services & Technology 2/25/2025 Pointers (4) float x, *p; p = &x; 1056 32 p 1052 16 16 1048 8 1040 0 address address 37

  38. Information Services & Technology 2/25/2025 Pointers (5) Depending on context, * can also be the dereferencing operator Value stored in memory location pointed to by specified pointer *p = 3.2; Common newbie error float *p; *p = 3.2; Wrong! p doesn t have value yet float x, *p; p = &x; *p = 3.2; correct

  39. Information Services & Technology 2/25/2025 Pointers (6) The name of an array is actually a pointer to the memory location of the first element a[100] a is a pointer to the first element of the array (a[0]) These are equivalent: x[0] = 4.53; *x = 4.53; 39

  40. Information Services & Technology 2/25/2025 Pointers (7) If p is a pointer and n is an integer, the syntax p+n means to advance the pointer by n memory locations These are therefore equivalent: x[4] = 4.53; *(x+4) = 4.53; 40

  41. Information Services & Technology 2/25/2025 Pointers (8) In multi-dimensional arrays, values are stored in memory with last index varying most rapidly (a[0][0], a[0][1], ) Opposite of Matlab and Fortran The two statements in each box are equivalent for an array declared as int a[20][20]: a[0][17] = 1; a[1][0] = 5; *(a+17) = 1; *(a+20) = 5; 41

  42. Information Services & Technology 2/25/2025 sizeof Some functions require size of something in bytes A useful function sizeof(arg) The argument arg can be a variable, an array name, a type Returns no. bytes in arg float x, y[5]; sizeof(x) ( 4) sizeof(y) (20) sizeof(float) ( 4) 42

  43. Information Services & Technology 2/25/2025 Dynamic Allocation Suppose you need an array, but you don t know how big it needs to be until run time. Use malloc function malloc(n) n is no. bytes to be allocated returns pointer to allocated space lives in stdlib.h 43

  44. Information Services & Technology 2/25/2025 Dynamic Allocation (cont d) Declare pointer of required type float *myarray; Suppose we need 101 elements in array malloc requires no. bytes, cast as appropriate pointer myarray = (float *) malloc(101*sizeof(float)); free releases space when it s no longer needed: free(myarray); 44

  45. Information Services & Technology 2/25/2025 Exercise 5 Modify dot-product program to handle vectors of any length Prompt for length of vectors Read length of vectors from screen Dynamically allocate vectors Don t forget to include stdlib.h so you have access to the malloc function solution 45

  46. Information Services & Technology 2/25/2025 if/else if/else Conditional execution of block of source code Based on relational operators < less than > greater than == equal <= less than or equal >= greater than or equal != not equal && and || or 46

  47. Information Services & Technology 2/25/2025 if/else if/else (cont d) if( x > 0.0 && y > 0.0 ){ z = 1.0/(x+y); }else if( x < 0.0 && y < 0.0){ z = -1.0/(x+y); }else{ printf( Error condition\n ); } 47

  48. Information Services & Technology 2/25/2025 if/else if/else (3) Can use if without else if( x > 0.0 && y > 0.0 ){ printf( x and y are both positive\n ); } 48

  49. Information Services & Technology 2/25/2025 Exercise 6 In dot product code, check if the magnitude of the dot product is less than using the absolute value function fabsf. If it is, print a warning message. With some compilers you would need to include math.h for the fabsf function With some compilers you would need to link to the math library by adding the flag lm to the end of your compile/link command solution 10 6 49

  50. Information Services & Technology 2/25/2025 Functions Function returns a single item (number, array, etc.) Return type must be declared Argument types must be declared Sample function definition: float sumsqr(float x, float y){ float z; z = x*x + y*y; return z; } 50

Related


More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#