Comparisons between C++ and Java (Appendix I)

Download Report

Transcript Comparisons between C++ and Java (Appendix I)

Chapter 4 Functions and
methods:
General syntax:
return_type function_name(par1, par2,…,parn)
Each should contain comments.
If it’s associated with a class, it’s
called a method.
Always write the functions with reuse
in mind.
Keep focus specific
Function should NOT combine two or
more tasks!!!! This limits their use by
those who want one or the other.
If function is to calculate and return a
value, don’t display it.
If a function is to display a value,
calculate it elsewhere.
If a function is to error check a
value before performing an action,
do not print error messages(p.
175).
Be cautious about catching
exceptions in functions.
Usually means functions are short.
return statement:
function ends when return is
executed. Specified value is returned
and used in context where the
function call is made.
A return statement must be reachable
for every possible condition.
Value returned must be consistent
with declared function type.
Exception: If function is type void then
no value is returned. Such functions
are sometimes called procedures.
Predicate:
function that returns a true or false.
Use meaningful names for functions
and parameters.
Follow standard conventions.
Creativity in design is good. Creativity
in defining names is not.
If functions are class methods, then
the header file must be included.
What is the problem with this?
#include <iostream>
using namespace std;
int main()
{
double x, y;
cin >> x;
y = half(x);
cout << y;
return 0;
}
double half(double x)
{
return 0.5*x;
}
If non-class functions are included
with main then
functions signatures (sometime called
prototypes) or implementations must
appear BEFORE they are invoked.
A function implementation may appear
AFTER it is invoked (or in another file) if
function signatures appear before or in
an included header file. See syntax and
example on p. 174.
If not done, different compilers may
respond differently.
All parameters are (by default) pass by
value. Note the difference from Java.
However, arrays are an exception to this.
Reference parameters: Explain and show
difference between
void swap (int x, int y)
{ int temp;
temp = x;
x = y; y = temp;}
and
void swap (int& x, int& y)
{ int temp;
temp = x; x = y; y = temp;}
Any type can be reference or value.
Note difference from java. This is
IMPORTANT!
NOTE: This does not work in C. This
is a C++ extension of C.
Deciding which variables are
reference and which are value is a
design issue.
In standard C, pass by reference was
done using:
void swap (int* x, int* y)
{ int temp; temp = *x; *x = *y; *y = temp;}
However, if a and b were type int,
then the call had to look like
swap(&a, &b);
& is the address operator in C.
It is the same operator used to
indicate a pass-by-reference
parameter in C++ (though it appears
after the parameter in the method
signature.
The multiple use of & is somewhat
unfortunate and does cause
confusion! Be careful!
const reference parameters:
Value parameters have higher overhead
(making copies of parameter). More of
an issue if parameter is an object with
many parts.
Reference parameters allow an object to
be changed.
Issue: How to lower overhead AND
protect an object from change.
A const reference allows the parameter
to be protected against change AND
lowers overhead of passing.
const type& parameter_name
Show what happens if previous swap function
is declared as
void swap (const int& x, const int& y)
Does NOT work in C!
Variable scope:
Extends from its declaration to the end
of the block it was declared in.
Declared in main => scope is main.
Declared in a function => scope is local
to the function.
Book mentions global variables.
Declared prior to main and all functions.
Accessible from within all. DO NOT
USE! Can cause name conflicts.
Testing and debugging
Do example (Section 4.11) converting a
number into a text string (for display on
payroll checks).
Download this program from the course
web site and test it. For what integers does
it fail?
Do his walkthrough on p. 195.
Alternative to inputting data for testing:
srand(time(0));
for (int i=1; i<100; i++)
{
n=rand() % 1000000;
cout << n << ": " << int_name(n) << endl;
}
Can be useful, but a less controlled
test procedure.
DO NOT confuse quantity of test data
with quality of test data
For functions, establish clear
preconditions for each parameter and
use exceptions to enforce them.
NOTE: This can apply to constructors
as well.
Chapter 3 Flow control:
if statements – pretty much like java. Look
at examples starting on p. 103.
Make sure brackets are aligned. This is a
readability aid.
The if/else statement -- Same as Java.
Do the selection operator. p. 104. Give
examples. It’s confusing syntax but you
need to be aware of it.
NOTE: What does the following do?
l = a>b?a>c?a:c:b>c?b:c;
Relational operators – same as java.
Test run the following code. What is
wrong?
int x;
cin >> x;
if (x=1)
cout << "X is equal to 1" << endl;
cin.get();
exit (0);
Be careful not to confuse = and ==.
C++ will accept either! Result
unpredictable.
Consider this example
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
double x, sum;
x = 0;
sum = 0;
while (x != 1.0)
{
x = x + 0.1;
sum = sum + x;
}
cout << " The sum is " << sum << endl;
cin.get();
return 0;
}
Note: advanced tip-difference
between errors and warnings. Must
eliminate errors. Should eliminate
warnings.
Comparing two float type numbers for
equality can be a problem.
Example, implement the following code (don’t forget to
#include <cmath>:
float x, y, z;
cout << " Enter a number";
cin >> x;
y=sqrt(x);
z=y*y;
cout << "x is " << x << "and z is " << z << endl;
if (x==z)
cout << "x and z are equal" << endl;
else
cout << "x and z are Not equal" << endl;
Look at ordering of multiple conditions from
page 109-10. Can produce incorrect
results.
See the switch statement. See highlighted
note on page 111.
Notes on nesting ifs and dangling elses.
Note example on page 112.
Nested branches (p. 112).
Discuss nested branches vs. conditions
with compound conditions.
Example logic to compute postage
costs
$5 to any of the 48 contiguous states
$7.50 to Alaska (AK)
$10 to Hawaii (HI)
$20 to any foreign country.
Is this OK?
if (country == "USA")
if (state == "HI")
charge = 10.00;
else
if (state == "AK")
charge = 7.50;
else
charge = 5;
else
charge = 20.00;
How about this?
if (country == "USA") && (state == "HI")
charge = 10.00;
if (country == "USA") && (state == “AK")
charge = 7.50;
If (country == “USA”) && (state != “HI)
&& (state != “AK)
charge = 5;
If (country != “USA”)
charge = 20.00;
Create test data for example on p.
113. (See also sections 4.14 And
4.15)
positive cases. Legitimate data you
expect the program to handle.
negative cases: data you expect the
program to reject.
boundary cases: specific values used in
conditions.
Account for ALL possible combinations.
test harness
used to feed inputs to a function/method.
Values can come from user inputs, values
generated in a loop, or randomly generated
values.
How do you know when output is correct?
May have to verify by hand calculation!!
Tedious but necessary. Sometimes you
can rely on other previously tested
methods. i.e. compare values returned by
your own square_root function with those
returned by sqrt().
In-class program: Calculate gross tax
given:
0% on first $200
5% on next $100
10% on the next $200
15% on the rest
Reduce by $10 for each deduction up to
a maximum of 6.
How many different sets of test data
would you generate?
Compound conditions.
EX: if ( x==1 || x==2 && y==2)
Which pairs of values make this true?
x=1 and y=3
x=3 and y=2
Compound conditions (&& for and; || for
OR). Best to NOT mix && and || operations
unless you really know what you are doing)
Example: x==0 || 1/x<1. What happens if x
is 0?
Compound conditions computed using lazy
evaluation. Evaluate conditions (left to
right) until the truth is determined. This
means that all conditions may NOT be
tested.
May not always be true with other
languages and compilers! Care is
needed!
Look at
cin >> x;
if ( x != 0 || x != 1)
cout << x << " bad input " << endl;
else
cout << x << " input is OK " << endl;
What values ofor x make this true?
Describe DeMorgans laws and relate
to the previous example.
The condition that is ALWAYS true.
This is the same as
if (!(x==0 && x==1).
While loops: pretty much the same as
in Java.
A few examples on page 123-4.
Watch out for infinite loops.
Describe the for loop. Just like Java. Can
declare variable in the for loop (p. 125). In
this case the variable scope is the loop
body.
Note the tips and errors on page 128-130.
Also a do loop. Compare it with the while
loop.
Input validation: Note example on page
133. What if non-digits were entered?
cin.fail() will return true if non-digits were
typed but the data stream should contain
digits.
Using cin as a condition is the opposite of
cin.fail() (example on p. 134)
Boolean variables and the the loop and a
half issue on page 135.
Discuss end of file checking (cin.eof()) on
p. 137.
Clearing the failure state of a stream
(cin.clear()) on p.138.
Loop invariant (Important for proving program correctness, something not
done in previous courses): assertion that is true every time a loop condition
is tested. Can be useful in proving correctness of loop activity. Example:
clever algorithm!!
r=1; b=a; i=n;
while (i>0)
{
if (i%2==0)
{
b=b*b
i=i/2
}
else
{
r=r*b
i–}
}
will always calculate an. (a and n are positive integers).
Claim: loop invariant is r*bi=an
Proof: True when loop starts. Next:
Let r’, b’, and i’ be the new r, b, and i
after one iteration of the loop. Need to
show r’*b’i’=an:
Suppose: i%2==0
Suppose: i%2 !=0
Let b’ = b*b and i’ = i/2.
Let r’ = r*b and i’ = i--
r*(b’)i’ = r*(b*b)i/2 = r*b2(i/2) = r*bi = an r’*bi’ = r*b*b(i-1) = r*bi = an
Discuss simulations, random numbers, pseudo
random numbers, and seeds. Do the Buffon
Needle experiment (p. 142) and a dice or card
game simulation.
Other examples on p. 143