02 c Cpp Differences
Transcript of 02 c Cpp Differences
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 1/23
C vs C++Chapter 1
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 2/23
Review of C/C++: Variables
Several different types
int integers (2, 7, 12)
float decimal numbers (3.14, 7.81)
char single characters (µa¶, µ4¶)
char[] used for strings (³Hello´, ³Hi´)
bool true or false
int a = 5;
char name[] = ³Compton´;
float f = 42.123;
C++ only!
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 3/23
Control Structur es (if-then-else)
if (condition1) {...
} else if (condition2) {...
} else {
..
.}
if (a < b ) {c = a;
} else if (b < a) {c = b;
} else {
c = d;}
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 4/23
Control Structur es (while/do-while)
while (condition1) {
.
.
.
}
do {
.
.
.
} while (condition2);
while (x > 0) {
x--;
}
do {
x--;
} while (x > 0);
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 5/23
Control Structur es (for )
for (x = initial value; condition; iteration) {
.
.
.
}
for (int x = 0; x < N; x++) {
A[x] = x;
}
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 6/23
Control Structur es (switch)
switch (expression) {case value1:
.
.
.
break;case value2:
.
.
.
break;default:...
}
switch (letter) {case µa¶:
a++; break;
case µb¶:
b++; break;
case µc¶:c++;
break;
default:}
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 7/23
Arrays
int values[4] = {5, 8, 2, 0};
char name[8] =
{µC¶, µo¶, µm¶, µp¶, µt¶, µo¶, µn¶, µ\0¶};
Group homogenous information together
REMEMBER WE START COUNTING AT 0! int v[4] means we actually have 4 elements:
v[0], v[1], v[2], and v[3].
There is no v[4]!
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 8/23
I/O
x = 5; printf(³Hello. x = %d\n´, x);
int i; printf(³Enter a number: ³);scanf(³%d´, &i);
In C, we used printf() and scanf()
In C++, we use cout and cin
Many ways to format strings for cout
More on using these modifiers later
.Net and C# go
back to this
somewhat
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 9/23
Functions
int average(int n1, int n2) {
return (n1+n2)/2;
}
int main() {
int a = 5;
int b = 6;
printf(³The average of a and b is: %d\n´,
average(a, b));
return 0;
}
Formal parametersC++
Actual parameters
(arguments)
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 10/23
struct Essentially a collection of variables
Used when heterogenous information needs to be
grouped
Can have arrays of structs (orthogonality)
By default, everything¶s public
Functions allowed within structs in C++ (class is astruct on steroids
struct ComputerCourse {int id;int nStudents;
};
int main() {ComputerCourse course;course.nstudents = 15;course.id = 322;
}
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 11/23
Pointers
int x = 10;
int * y = &x;
*y = 20;
Special variable that only holds memory addresses Holds the location (address) of information, not the
information itself
Two operators: address-of and dereferencing operators
&v ariable ³the address of variable´
* pointer ³data at the address contained in pointer ́
10x
y
Name Address Value
0x01
0x08 0x01
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 12/23
C and C++
C++ Improves on many of C's features
Has object-oriented capabilities
Increases software quality and reusability
Allows faster and better development of large projects Developed by B jarne Stroustrup at Bell Labs
Called "C with classes"� C++ (increment operator) - enhanced version of C
Superset of C Can use a C++ compiler to compile C programs
Gradually evolve the C programs to C++
C++ is much stricter than C
ANSI C++ Final version at http://www.ansi.org/
ANSI 1998
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 13/23
Some diff er ences & conventions
File extensions
C files: .c
C++ files: .cpp (which we use), .cxx, .C (uppercase)
Header files: .h
Differences
C++ allows you to "comment out" a line by preceding it with //
For example: // text to ignore
<iostream> - input/output stream header file (no .h!)
Return types - all functions must declare their return type
C does not require it, but C++ does
Variables in C++ can be declared almost anywhere
In C, required to declare variables in a block, before any
executable statements
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 14/23
Input/Output
Input/Output in C++ Performed with streams of characters
Streams sent to input/output objects
Data inserted into or extracted out of these streams
Output
std::cout - standard output stream (connected to screen) << stream insertion operator ("put to")
std::cout << "hi"; Puts "hi" to std::cout, which prints it on the screen
Input
std::cin - standard input object (connected to keyboard)
>> stream extraction operator ("get from")
std::cin >> myVariable; Gets stream from keyboard and puts it into myVariable
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 15/23
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 16/23
cin
Imagine a stream of data flowing from the keyboard tothe computer/memory
istream = INstream
You can extract a value from this stream
Just use the extraction operator to get a value fromthe stream of data and put it in your variable
cin >> intVariable;
intVariable
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 17/23
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 18/23
Input/Output modifiers
std::endl "end line"
Stream manipulator - prints a newline and flushes outputbuffer
Some systems do not display output until "there is enoughtext to be worthwhile" std::endl forces text to be displayed
using directive statements Allow us to remove the std:: prefix
Just add ³using namespace std;´ or ³usingstd::cout;´
Discussed further later
Cascading Can have multiple << or >> operators in a single statement
(³chaining´)std::cout << "Hello " << "there" << std::endl;
Better!
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 19/23
Namespaces
Sets the scope of variables and identifiers
(names), including functions!
All unnamed namespaces are in global scope Just add ³using namespace std;´ directive
Then you can just say cout instead of std::cout
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 20/23
IO Manipulation
Use ³#include <iomanip>´ to access the
input/output manipulation functions
setw(int) set width of the fieldsetprecision(int) sets # of decimal places
setiosflags(ios::left) set alignment, etc.
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 21/23
Scopes, Casts, & Manipulators
Unary scope resolution operator (::) Access global variables if a local variable has same name
Instead of variable use ::variable
static_cast <newType> (variable)
Creates a copy of variable
of typenewType
Convert ints to floats, etc.
Stream manipulators
Can change how output is formatted
setprecision - set precision for floats (default 6 digits)
setiosflags - formats output setwidth - set field width
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 22/23
1. Initialize globalconst PI
1.1 cast globalPI to a localfloat
2. Print local and
global values of PI
2.1 Vary precisionand print local PI
1 // casts.cpp
2 // Using the unary scope resolution operator
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7 using std::ios;8
9 #include <iomanip>
10
11 using std::setprecision;
12 using std::setiosflags;
13 using std::setw;
14
15 const double PI = 3.14159265358979;
16
17 int main()
18 {
19 const float PI = static_cast < float >( ::PI );
20
21 cout << setprecision( 20 )
22 << " Local float value of PI = " << PI
23 << "\nGlobal double value of PI = " << ::PI << endl;
24
25 cout << setw( 28 ) << "Local float value of PI = "
26 << setiosflags( ios::fixed | ios::showpoint )
27 << setprecision( 10 ) << PI << endl;
28 return 0;
29 }Local float value of PI = 3.141592741012573242
Global double value of PI = 3.141592653589790007Local float value of PI = 3.1415927410
8/6/2019 02 c Cpp Differences
http://slidepdf.com/reader/full/02-c-cpp-differences 23/23
Typecasting
Automatic type conversion
Converted to largest data type in an expression
Right side of assignment converted to data typeof left side
Can lead to semantic errors!