
Compare the following three programs which appear to show the transition from C to C++ to Java
Tester1.c
#include < stdio.h>
struct intClass{
int i;
};
int main(){
struct intClass i1;
i1.i=5;
struct intClass j1;
j1 = i1;
j1.i=7;
printf("%i\n",i1.i);
}
Tester1.cpp
#include < stdio.h>
class intClass{
public:
int i;
};
int main(){
intClass i1;
i1.i=5;
intClass j1;
j1 = i1;
j1.i=7;
printf("%i\n",i1.i);
}
Tester1.java
import java.io.*;
class intClass{
public int i;
}
class Tester1 {
public static void main(String args[]){
intClass i1 = new intClass();
i1.i=5;
intClass j1;
j1 = i1;
j1.i=7;
System.out.println(i1.i);
}
}
/siegel/home/public_html%a.out 5 /siegel/home/public_html%a.out 5 /siegel/home/public_html%java Tester1 7
The key to what is happening is in the treatment of the common line
j1=i1;
In C and C++, the semantics of "=" is copy content.
In Java the semantics is copy reference. Thus, in Java, both j1 and i1 point to the same storage after the "assignment" statement and, hence, a change in the content of the common storage is reflected in both references.
By the way, to make the situation slightly more complex, for primative data types, int etc. , "assignment" is copy content.
Finally, the Java statement
intClass j1;
does not even allocate storage for i. Much more on this point to follow.
Finally, in C and C++, pointers provide the same semantics, as the following example shows
test.c
#include <stdio.h>
void main(void){
struct Int{int i;};
struct Int *i1,*j1;
struct Int k;
k.i=5;
i1=&k;
j1=i1;
j1->i=7;
printf("%i\n",i1->i);
}
Output
/accounts/faculty/siegel/Cfiles% cc test.c /accounts/faculty/siegel/Cfiles% a.out 7