from java to c
-
Upload
vo-hoa -
Category
Technology
-
view
77 -
download
0
Transcript of from java to c
From Java to C/C++
Mechanism
Exception Handling
Memory managemen
t
OOP
Function
PointerData structure
Variable & constant
Storage class
specifiers
Data type
Package
OUTLINE
Java vs. C/C++
AlgorithmsLogic
Coding skill
High levelOOP only
Byte-code
JVM
Well supported build-in library
Pointer
Manual memory management
No well supported build-in library
Cross platform
Support UI lib
No standard UI lib
Both OOP & non-OOP
GC
Applet
Midlet
main()
main()C/C++
Filename same as classname
Hello world
C/C++
class HelloWorld{ public static void main(String args[]) { System.out.println("Hello World!"); }}
#include "stdio.h"void main(){ printf("Hello World");}
HelloWorld.java
Anyname.cpp
C/C++ compiler
Building
Java compiler
Achieve
.jar
.java
.class
Byte code
javac.exe Prep. source
.o
Linker
Executable
preprocessor
gcc / g++cl
gcce/arm
.h.cpp/.c
Use cpp.exe for preprocessing if
need
Processor
Running
JVM
OS
C/C++ executable
Java executable
java.exe
Package
Mechanism
Exception Handling
Memory managemen
t
OOP
FunctionPointer
Data structure
Variable & constant
Storage class
specifiers
Data type
OUTLINE
Package
C/C++
packageimport
namespace
using namespace
package illustration;import java.awt.*;public class Drawing { . . .}
using namespace std;namespace demo{
class DemoClass{
…};
}
Use: ‘ :: ’<namespace>::<subnamepace>::…::< subnamepace >::<class>::< static properties/functions>MyNamespace::MyClass::MyStaticFunction()
<namespace>::<subnamepace>::…::< subnamepace >::<var/function>std::cin
Use: ‘ . ‘ or ‘ -> ’ for accessing class’ properties, fucntionsMyNamespace::MyClass *cA = new MyNamespace::MyClass ()cA->Foo1();(*cA).Foo2();
Scope resolutionUse: ‘ . ’<package>.<subpackage>…<subpackage>.<class>.<properties/functions>
java.lang.Math.abs(a)
C/C++. or -> when & why
Use import for shorten call:import java.lang.Math;Math.abs(a);
Use using namespace for shorten call:using namespace std;cin >>a;
Data type
Package
Mechanism
Exception Handling
Memory managemen
t
OOPFunction
Pointer
Data structure
Variable & constant
Storage class
specifiers
OUTLINE
Primitive Data TypesJava C/C++ (32 bits) Range
void void n/a
char unsigned short / unsigned char 2 bytes / 1 byte
byte char / signed char 1 byte-128 … 127
short short / short intsigned shortsigned short int
2 bytes-215 … (215 – 1)
int int / signed intlong / long int / signed long / signed long int
4 bytes-231 … (231 – 1)
long long long / signed long long 8 bytes-263 … (263 – 1)
boolean bool 1 byteTrue/false
float / double float / double 4 bytes/ 8 bytes
Primitive Data Types• NO “unsigned” (excepted char is an unsigned type)• Set to “default value” when declare
C/C++• Separated to signed & unsigned• NO “default value”• No standard string, use char*
Type Range
char • (signed) char: -128 … 127• unsigned char: 0 … 255
short • (signed) short: -215 … (215 – 1)• unsigned short: 0 … (216 – 1)
int / long • (signed) int/long: -231 … (231 – 1)• unsigned int/long: 0 … (232 – 1)
long long • (signed) long long: -263 … (263 – 1)• usigned long long: 0 … (264 – 1)
C/C++Use sizeof() to get size of a type:
char c = 0; sizeof(c) 1
New type definition
0C/C++ only0Use typedef
typedef int Mytype;typedef int MyArr[5];
Mytype var1;MyArr arr;
C/C++
Storage class
specifiersData type
Package
Mechanism
Exception Handling
Memory managemen
tOOP
Function
Pointer
Data structure
Variable & constant
OUTLINE
Storage class specifiers
Key-work Desc. Example
auto Go out of scope once the program exits from the current block
auto int var1;int var2;
register Stored in a machine register if possible register int var;
static Allocated when the program begin and deallocated when the program ends
static int var;
extern Specify that the variable is declared in a different file. Compiler will not allocate memory for the variable
extern int DefineElseWhere;
Static / non-static
int m_iVar;static int s_StaticVar;
C/C++
Why extern?
0No need to notify compiler where is the classes/ variable/ functions
C/C++ 0MUST notify compiler where is the classes / variables/ functions were declared
0Use extern to notify that they were declared somewhere
Variable & constant Storage
class specifiers
Data type
Package
Mechanism
Exception Handling
Memory managemen
t
OOP
Function
Pointer
Data structure
OUTLINE
Variable
Local variable
Static variable
Register variable
Global variable
C/C++
Variable
C/C++
int todo(){
unsigned int Age;float a = 10;System.out.println(Age);
}
Fail, Age is not set value before using
int todo(){
unsigned int Age;float a = 10;printf("%d", Age);
}
C/C++
Age is not set value, but still OK in C/C++
Local variable
Static variable
Register variable
Global variable
No default value caused many mysterious bug
Variable0 Static duration
C/C++
static int var2;struct C { void Test(int value) { static int var; cout <<var <<endl; var = value; }};
class MyClass{public: static int s_Var;};int MyClass::s_Var = 0;
int main() { C c1, c2; c1.Test(100); c2.Test(100); var2 = 10000; MyClass::s_Var = 100;}
Local static
Global static
Set default to zerovar = 0
Value must be set outside class
definition
Static Class member
Local variable
Static variable
Register variable
Global variable
Variable
0 C/C++ only0 Stored in a machine register if
possible0 Improve performance
C/C++register int index = 0;
Local variable
Static variable
Register variable
Global variable
Variable
C/C++ only
C/C++
int globalVar = 0;int main() { int localVar = 10; cout <<globalVar <<endl; cout <<localVar <<endl;}
Local variable
Static variable
Register variable
Global variable
Constants
Use any where
Use as static data of classclass A{ final static int k_value = 0;}
const int A = 0;
C/C++
Data structure
Variable & constant
Storage class
specifiers
Data type
Package
MechanismException Handling
Memory managemen
t
OOP
Function
Pointer
OUTLINE
Data structure
class
struct
enum
C/C++
union
Data structure
0Used to set up collections of named integer constants
class
struct
enum
C/C++
union
enum MyEnumType { ALPHA, BETA, GAMMA };enum MyEnumType x; /* legal in both C and C++ */MyEnumType y; // legal only in C++
C/C++
public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
Data structure
class
struct
enum
C/C++
union
class JavaClass{ public JavaClass() {…} private void Toso() {…} }
class CClass{ public: CClass() {…} ~CClass(); private: void Toso() ;};
#include "Any_name.h" void CClass::Todo(){ …}CClass::~CClass(){ …}
JavaClass.java
Any_name.h Other_name.cpp
C/C++
Data structure0 C/C++ only0 A user-defined type that uses same
block of memory for every its list member.
class
struct
enum
C/C++
union union NumericType{ int iValue; long longValue; double dValue; };
int main(){ union NumericType Values = { 10 }; // iValue = 10 printf_s("%d\n", Values.iValue); Values.dValue = 3.1416; printf_s("%f\n", Values.dValue);} C/C++
0 4 8
iValuelongValue
dValue
Data structure0 C/C++ only0 The C++ class is an extension of the C
language structure0 Default access:
0 Class: private0 Struct: public
class
struct
enum
C/C++
unionclass X { // private by default int a;public: // public member function int f() { return a = 5; };};
struct Y { // public by default int f() { return a = 5; };private: // private data member int a;};
Should be used for storing only.
C/C++See more: structure alignment
Pointer
Data structure
Variable & constant
Storage class
specifiers
Data type
PackageMechanism
Exception Handling
Memory managemen
t
OOP
Function
OUTLINE
Pointer0 No explicit pointer in Java0 Array and object are implicit pointer0 Explicit null value for array/object
C/C++
Bicycle bike1 = new Bicycle();int[] arr = new int [100]
bike1
arr
Two type of variable: o Data type
o Pointer type Implicit null value, aka zero value (0)
int i;int *p = &i;char *st = new char[10];char *p2 = st;char st2[] = "ABC“;char p3[] = st2;
i p st2 = ABC st p2
null
0x0 NULL
sizeof(p) = ?sizeof(st2) = ?
p = ?*p = ?&p = ?
String
0No standard string in C/C++0Use char*, or char[] instead0String in C/C++ is array of byte, end with ‘\0’
char *st = "String";
S t r i n g \0st
char st2[] = "String";
S t r i n g \0
st2
st = ?&st = ?*st = ?
st2 = ?&st2 = ?*st2 = ?
Function pointer0 C/C++ only0 Is variable store address of a function
// C void DoIt (float a, char b, char c){……}void (*pt2Function)(float, char, char) = DoIt;
// usingpt2Function(0, 0, 0);
// C++class TMyClass{public: void DoIt(float a, char b, char c){……};};void (TMyClass::*pt2Member)(float, char, char) = &TMyClass::DoIt;
// usingTMyClass *c = new TMyClass();(c->*pt2Member)(0, 0, 0); C/C++
Object0Always use “new”0Object variable hold reference
C/C++
0 Support two kinds:0 Object variable hold values
0 Object variable hold reference (through pointer)
Bicycle bike1 = new Bicycle();bike1.changeCadence(50);
Bicycle bike1; bike1.changeCadence(50);
Bicycle *bike2 = new Bicycle(); bike2->changeCadence(50);(*bike2).changeCadence(100);
bike1 vs. bike2?
Function
Pointer
Data structure
Variable & constant
Storage class
specifiers
Data typePackage
Mechanism
Exception Handling
Memory managemen
t
OOP
OUTLINE
Function
C/C++
• Declare inside class• Pass-by-value only• No need prototype
• Declare anywhere• Pass-by-value / pass-by-reference optional• Need prototype
How about array and
object?
Function
0Function Prototypevoid todo();void main(){ todo();}void todo(){ ……}
0Pass by value / Pass by referencevoid todo(int pass_by_value, int &pass_by_ref)
“&” is for pass by reference
prototype
C/C++
Pass-by-valueC/C++
void swap1(int i, int j) void swap1(int i, int j)void swap1(MyClass obj1, MyClass obj2)
B’
swap
B
A
A’
B’
A’
B
A
tmp = A;A = B;B = tmp
Pass-by-value (2)
A’
B’
A’
B’
A
B
A
B
Copy value (addr. of data)
swap2
C/C++void swap2(MyClass obj, MyClass obj2) void swap2(MyClass* obj, MyClass* obj)
tmp = A;A = B;B = tmp
Pass-by-ref
void swap3(MyClass &obj1, MyClass &obj2)
Not available
C/C++
B
swap
B
A
A
B
A
B
A
tmp = A;A = B;B = tmp
OOP
Function
Pointer
Data structure
Variable & constant
Storage class
specifiersData type
Package
Mechanism
Exception Handling
Memory managemen
t
OUTLINE
OOP
Interface
Pure virtual class
C/C++
Abstract class
Single inheritance
Multiple inheritance
Constructor
Destructor
super
virtual
Pure virtual function
public private
protected
friend
OOP Theory
final
OOP - Inheritancepublic class MyDog extends Dog implement ITalkable, ISmileble{public:
MyDog(){}//ITalkable implementvoid DoTalk();//ISmileblevoid DoSmile();void Todo() { super.Todo();}
}
C/C++
public class MyDog:public Dog,public ITalkable, protected ISmileble{public:
MyDog(){}~MyDog() {}//ITalkable implementvoid DoTalk();//ISmileblevoid DoSmile();void Todo() { Dog::Todo();}
}
Destructor, called when object is deallocated
OOPAbstract class vs. Pure virtual class
public abstract class GraphicObject { // declare fields // declare non-abstract methods abstract void draw();}
C/C++
class classname{ public:
virtual void virtualfunctioname() = 0;};
Pure virtual function
OOP - virtual
• Function are virtual by default• Use final to prevent override
C/C++
• Use key word virtualvirtual int foo()
class ClassA{public:
ClassA() {}virtual void Todo();
};
class ClassB: public ClassA{public:
ClassB():ClassA() {}void Todo();
}
OOP - virtual
class ClassA{public:
ClassA() {}virtual void Todo1() {printf("TodoA1\n");}void Todo2() {printf("TodoA2\n");}
};
class ClassB: public ClassA{public:
ClassB():ClassA() {}void Todo1() {printf("TodoB1\n");}void Todo2() {printf("TodoB2\n");}
};
void main(){
ClassA *Obj = new ClassB();Obj->Todo1();Obj->Todo2();
} C/C++
Output ?
OOP – virtual destructor
class ClassA{public:
ClassA() {}virtual ~ClassA() {printf("DeleteA\n");}
};
class ClassB: public ClassA{public:
ClassB():ClassA() {}~ClassB() {printf("DeleteB\n");}
};
void main(){
ClassA *Obj = new ClassB();delete Obj;
} C/C++
Without virtual, only destructor of ClassA is called
Memory managemen
tOOP
Function
Pointer
Data structure
Variable & constant
Storage class
specifiers
Data type
Package
Mechanism
Exception Handling
OUTLINE
#define NULL 0int main() { // Allocate memory for the array char* pCharArray = new char[100]; // Deallocate memory for the array delete [] pCharArray; pCharArray = NULL;
// Allocate memory for the object CName* pName = new CName; pName->SetName("John");
// Deallocate memory for the object delete pName; pName = NULL;}
Memory management
C/C++
Use GC to collect garbage data
• No GC mechanism, handle manually• Use delete / free to clean up
unused heap• Memory leak problem
C/C++
Exception Handling Memory
management
OOP
Function
Pointer
Data structure
Variable & constant
Storage class
specifiers
Data type
Package
Mechanism
OUTLINE
Exception handling
Well supported build in exception
try{ int zero = 0; int val = 1/zero;}catch (Exception E){ E.printStackTrace();}
C/C++Manual exception handling
class DBZEx {};void div(int num1, int num2){ if (num2 == 0) throw (DBZEx ());}void main(){ try { div(1, 0); } catch (DBZEx ex) { printf(" DBZ Exception "); } catch (...) { printf("Unkown exception"); }}
The end!
Appendix A: Preprocessor
Appendix A: preprocessor
0Handle directive: #include0Macro definition: #define, #undef0Condition inclusion: #if, #ifdef, #ifndef, #if defined(…), #elif, #else, #endif
0Refs:0 http://en.wikipedia.org/wiki/C_preprocessor0 http://msdn.microsoft.com/en-us/library/b0084kay.aspx0 http://gcc.gnu.org/onlinedocs/cpp/index.html0 http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf
Appendix A: preprocessor
#include0 Include another file.
#include <stdio.h> int main (void){ printf("Hello, world!\n"); return 0;}
The preprocessor replaces the line #include <stdio.h> with the system header file of that name
Appendix A: preprocessor
#define0 Define a macro, object-like and function-like
#define Min(x, y) ((x)<(y))?(x):(y)
Object-like #define PI 3.14
Function - like
#define PI 3.14#define Min(x, y)((x)<(y))?(x):(y)void main(){
int pi = PI;int num = Min(pi, 2);
}
#undef0 Un-defined a macro
Appendix A: preprocessor
#if, #ifdef, #ifndef, #if defined(…)#elif, #else, #endif
0 Directives can be used for conditional compilation.
#ifdef _WIN32# include <windows.h> #else # include <unistd.h> #endif
#if VERBOSE >= 2 print("trace message");
#endif
#if !defined(WIN32) || defined(__MINGW32__) ... #endif
Prevent duplicate declaration
void Todo();//something else
H1.h
#include "H1.h"//something else
H2.h
#include "H1.h"#include "H2.h"
//something else
Main.cpp
//from H1void Todo();
H2.h preprocess
//from H1void Todo();
//from H2void Todo();
//something else
Main.cpp preprocess
duplicated
Prevent duplicate declaration
0Use #ifndef
#ifndef __H1_H__#define __H1_H__
void Todo();//something else
#endif
H1.h
#pragma once
void Todo();//something else
H1.h
0 Use #pragma once