c++ for java programmers chapter 2. fundamental data types timothy budd
TRANSCRIPT
CommentsComments
JavaJava
// Comment thru end of line// Comment thru end of line
/* Multi line comments /* Multi line comments extend until the final */extend until the final */
C++C++
C++ can use both C++ can use both styles of commentsstyles of comments
C uses only the C uses only the second stylesecond style
22
33
Integers
Java Integer Internal Representation• short - 16 bit
• integer -32 bit
• long - 64 bitshort int x; // declare x as a small integer
long y; // declare y as long integer
C++ Integer Internal Representation• long and/or short may have the same size as integer
• int is usually the size of native target machine
44
C++ Integer
An unsigned integer can only hold nonnegative values
int i = -3;
unsigned int j = i;
cout << j << endl; // will print very large positive integer
Assigning a negative value to an unsigned variable is confusing (but legal)
Integer division involving negative numbers is platform dependent, but following equality must be preserved: a == (a / b) * b + a % b
55
Integers
Never use the remainder operator with negative values.
unsigned long a; // for largest integer valuessigned short int b; // for smallest integersINT_MAX, INT_MIN, SHRT_MAX, etc. are constants which define the limits
C++ does not recognize the Byte data type in Java. Instead signed char is often used to represent byte-sized quantities.
66
Characters
8 bit quatity - Legal to perform arithmetic on characters Character can be signed or unsigned. w_char - recent addition wide character
alias for another interger type such as short.(UNICODE > 1 byte)
77
Booleans
Recent addition - bool Historical boolean representation
nonzero – true (usually 1 or -1) zero - false
Integer and pointer types can be used as boolean values.
Cannot be signed or unsigned.
88
Examples of Booleans
int i = 10;while (i) { // will loop until i is zero
...i--;
}
while (*p++ = *q++) ;
bool test = true;int i = 2 + test; // i is now 3test = test - 1; // test is now 0, or false
99
Booleans
Even pointer values can be used as boolean False if it is null, true otherwise..
aClass * aPtr; // declare a pointer variable
...
if (aPtr) // will be true if aPtr is not null
Legacy code can contain different boolean abstractions.
1010
Bit Fields
Seldom used feature Programmer can specify explicitly the
number of bits to be used.
struct infoByte {
int on:1; // one-bit value, 0 or 1
int :4; // four bit padding, not named
int type: 3; // three bit value, 0 to 7
};
Bit Fields: Practical Example Bit Fields: Practical Example Frequently device controllers and Frequently device controllers and
the OS need to communicate at a the OS need to communicate at a low level. low level.
Example: Example: Disk Controller Register Disk Controller Register We could define this register easily We could define this register easily with bit fields: with bit fields:
struct DISK_REGISTER struct DISK_REGISTER { { unsigned ready:1; unsigned ready:1;
unsigned error_occured:1; unsigned error_occured:1; unsigned disk_spinning:1; unsigned disk_spinning:1; unsigned write_protect:1; unsigned write_protect:1; unsigned head_loaded:1; unsigned head_loaded:1; unsigned error_code:8; unsigned error_code:8;
unsigned track:9; unsigned track:9; unsigned sector:5; unsigned sector:5; unsigned command:5; }; unsigned command:5; };
1111
1212
Floating Point Values
float, double, long double
int i;
double d = 3.14;
i = d; // may generate a warning
Never use float; use double instead. math routines generally will not throw an
exception on error
1313
Floating Point Values
Always check errno
double d = sqrt(-1); // should generate error
if (errno == EDOM)
... // but only caught if checked
Java: Nan, NEGATIVE INFINITY, POSITIVE INFINITY
1414
Enumerated Values
Nothing in commonwith Enumeration class in Java
enum declaration in C++
enum animal {dog, cat, horse=7, cow};
enum color {red, orange, yellow};
enum fruit {apple, pear, orange};
// error: orange redefined
1515
Enumeration Values
Can be converted into integers and can even have their own internal integer values explicitly specified.
enum shape {circle=12, square=3, triangle};
Can be assigned to an integer and incremented, but the resulting value must then be cast back into the enumrated data type before
fruit aFruit = pear;
int i = aFruit; // legal conversion
i++; // legal increment
aFruit = fruit(i); // fruit is probably now orange
i++;
aFruit = fruit(i); // fruit value is now undefined
1616
Type Casting Cast operation can be written by Cast operation can be written by
type(value) or older (type)value syntax.type(value) or older (type)value syntax. Not legal to change a pointer type.Not legal to change a pointer type.
int* i; // same as int *i;char* c;
c = char* (i); // error: not legal syntax
static_cast would be even better.
double result = static_cast<double>(4)/5;
1717
The void type
In Java, used to represent a method or function that does not yield a result.
In C++, type can also be used as a pointer type to describe a “universal” pointer that can hold a pointer to any type of value.
Similar to Object in Java
1818
Arrays
An array need not be allocated by using new directive as in Java.
The number of elements determined at compile time.
int data[100]; // create an array of 100 elements
The number of elements can be omitted.char text[ ] = "an array of characters";
int limits[ ] = {10, 12, 14, 17, 0};
1919
Arrays
Not legal to place the square brackets after type as in Java
double[ ] limits = {10, 12, 14, 17, 0}; // legal Java, not C++
The size can be omitted when arrays are passed as arguments to a function.
// compute average of an array of data values
double average (int n, double data[ ] )
{ double sum = 0;
for (int i = 0; i < n; i++) {
sum += data[i];}
return sum / n; }
2020
Structures & Classes
struct myStruct // holds an int, a double, AND a pointer {
int i;
double d;
anObject * p;
};
Struct Class
Members public by default Members private by default
In C, data members only In C, no classes
2121
Unions
Similar to a structure, but the different data fields Similar to a structure, but the different data fields all share the same location in memory.all share the same location in memory.
// can hold an int, a double, OR a pointer
union myUnion {
int i;
double d;
anObject * p;
};
Object-orienteObject-oriented languages made d languages made unions unions unnecessary by introducing unnecessary by introducing polymorphic polymorphic variablesvariables
Object Values
C++ uses copy semantics.
class box {class box { // C++ box// C++ boxpublic: int value;public: int value;
};};
box a; // box a; // note, no explicit allocationnote, no explicit allocationbox b;box b;
a.value = 7;a.value = 7;b = a;b = a;a.value = 12;a.value = 12;cout << "a value " << a.value << endl;cout << "a value " << a.value << endl;
cout << "b value " << b.value << endlcout << "b value " << b.value << endl;;// a & b are different objects // a & b are different objects
Java uses reference semantics
class box {class box { // Java box // Java box public int value;public int value;
}}
box a = new box();box a = new box();box b;box b;
a.value = 7; a.value = 7; // set variable a// set variable ab = a; b = a; // assign b from a// assign b from aa.value = 12; a.value = 12; // change variable a// change variable aSystem.out.println("a value “+ a.value);System.out.println("a value “+ a.value);System.out.println("b value “+ b.value);System.out.println("b value “+ b.value);
// a & b refer to the same object// a & b refer to the same object
2222
Reference Variables (alias)
JAVAJAVA
box a = new box(); box a = new box();
box c = new box();box c = new box();
// java reference assignment// java reference assignment
box b = a;box b = a;
// reassignment of reference// reassignment of reference
b = new box();b = new box();
C++C++
box a;box a;
box c;box c;
// C++ reference assignment // C++ reference assignment
box & b = a;box & b = a;
// error: not permitted to // error: not permitted to reassign referencereassign reference
b = c;b = c;2323
2424
Functions
C++ permits the definition of functions (and variables) that are not members of any class.
// define a function for the maximum of two integer valuesint max (int i, int j) {
if (i < j) return j;return i;
}int x = ...;int y = ...;int z = max(x, y);
2525
Functions
Prototypes are necessary in C++ as every function name with its associated parameter types must be known to the compiler.
// declare function max defined elsewhere
int max(int, int);
2626
Order of Argument Evaluation
In Java, argument is evaluated from left to right.String s = "going, ";
printTest (s, s, s = "gone ");
void printTest (String a, String b, String c)
{
System.out.println(a + b + c);
}
In C++, order of argument evaluation is In C++, order of argument evaluation is undefined and implement dependent (usually undefined and implement dependent (usually right to left)right to left)
2727
The function main
In C++, main is a function outside any class. Always return zero on successful completion of the
main program.int main (int argc, char *argv[ ])
{
cout << "executing program " << argv[0] << '\n';
return 0; // execution successful
}
The first command line argument in C++ is always the application name.
A lot of old legacy code uses: void main()
2828
Altenative main Entry points
Individual libraries may provide their own version of main and then require a different entry point.
Many Windows graphical systems come with their own main routine already written, which will perform certain initializations before invoking a different function such as WinMain.
C/C++ compilersC/C++ compilers
Visual StudioVisual Studio Borland C++ BuilderBorland C++ Builder Linux cc, c++, gcc, g++Linux cc, c++, gcc, g++
• gcc = ccgcc = cc C programs onlyC programs only• g++ = c++g++ = c++ C or C++ programsC or C++ programs• Actually all 4 compilers are the same programs Actually all 4 compilers are the same programs
making different assumptions based on input file making different assumptions based on input file name or contentsname or contents
Dev-C++ a good g++ compiler for PC’sDev-C++ a good g++ compiler for PC’s
2929
Linux G++Linux G++
Command SyntaxCommand Syntax
g++ filenameg++ filename
Input file should have Input file should have extension .c, .cc, .cxx, .cpp, .c++extension .c, .cc, .cxx, .cpp, .c++Usually C-programs - .cUsually C-programs - .c C++ programs - .cpp C++ programs - .cppAlthough g++ is pretty smart at figuring it out Although g++ is pretty smart at figuring it out regardless of the extensionregardless of the extension
Most other compilers are less tolerantMost other compilers are less tolerant
3030
Linux G++ (cont)Linux G++ (cont)
Output file by default is a.outOutput file by default is a.out Output filename can be specified with –oOutput filename can be specified with –o
g++ -o outfilename filename.cpp g++ -o outfilename filename.cpp
3131
Simple ProgramsSimple Programs
JAVAJAVA
public class HelloWorldpublic class HelloWorld
{{
public static void main(String[] args)public static void main(String[] args)
{ { System.out.println("Hello World"); System.out.println("Hello World");
}}
} }
CC
#include <stdio.h>#include <stdio.h>
void main (int argc, char argv[])void main (int argc, char argv[])
{{
printf(“Hello World\n);printf(“Hello World\n);
}}
3232
Simple ProgramsSimple Programs
CC
#include <stdio.h>#include <stdio.h>
void main ()void main ()
{{
printf(“Hello World\n”);printf(“Hello World\n”);
}}
C++C++
#include <iostream>#include <iostream>
using namespace std;using namespace std;
void main ()void main ()
{{
cout << “Hello World” << cout << “Hello World” << endl; endl;
}}
3333
Actually some would consider a Actually some would consider a void main function bad form, so …void main function bad form, so …
CC
#include <stdio.h>#include <stdio.h>
int main ()int main ()
{{
printf(“Hello World\n”);printf(“Hello World\n”);
return 0;return 0;
}}
C++C++
#include <iostream>#include <iostream>
using namespace std;using namespace std;
int main ()int main ()
{{
cout << “Hello World” << endl;cout << “Hello World” << endl;
return 0;return 0;
}}
3434