C++, Objective C, Java, C# 详细比较和区别

来源:互联网 发布:失踪儿童数据库 编辑:程序博客网 时间:2024/06/11 23:49

primitive types | arithmetic and logic | strings | regexes | dates and time | arrays | dictionaries | functions
execution control | files | directories | processes and environment | libraries and namespaces | objects | generic types
reflection | web | contact

c++ (1983)objective c (1986)java (1995)c# (2001)hello word$ cat hello.cpp
#include <iostream>
using namespace std;
int main(int argc, char**arg) {
  cout << "Hello, World!" << endl;
}
$ g++ hello.cpp
$ ./a.out
Hello, World!$ cat hello.m
#include <stdio.h>
int main(int argc, char **argv) {
  printf("Hello, World!\n");
}
$ gcc hello.m
$ ./a.out
Hello, World!$ cat Hello.java
public class Hello {
  public static void main(String[] args) {
    System.out.println("Hello, World!");
  }
}
$ javac Hello.java
$ java Hello
Hello, World!$ cat hello.cs
using System;
public class Hello {
  public static void Main() {
    Console.WriteLine("Hello, World!");
  }
}
$ mcs hello.cs
$ mono hello.exe
Hello, World!version used
 g++ 4.2gcc 4.2java 1.6mono 2.10 (C# 4.0)version
 $ g++ —version$ gcc —version$ javac -version$ mcs —versionlibraries used
 STL and BoostFoundation FrameworkJava APIBase Class Librarysource, header, object file suffix.cpp .hpp .o.m .h .o.java none .class.cs none .exe or.dllnull
 NULLNULLnullnullprintf
 cout << "count: " << 7 << endl;printf("count: %d\n", 7);System.out.printf("count: %d", 7);System.Console.WriteLine("count: {0}", 7);case and underscores in namesA_MACRO_NAME
AClassName
AMethodName() or a_method_name()
a_variable_nameA_MACRO_NAME
AClassName
[obj aMsgName:arg aLabelName:arg]
aVariableNameAClassName
aMethodName()
aVariableNameAClassName
AMethodName()
aVariableNamecoalesce
 string s1 = s2 || "was null";NSString *s1 = s2 || @"was null";String s1 = s2 == null ? "was null" : s2;string s1 = s2 ?? "was null";primitive types c++objective cjavac#declare primitive type on stackint i;
int j = 3;
int k(7);int i;
int j = 3;int i;
int j = 3;int i;
int j = 3;allocate primitive type on heapint *ip = new int;#include <stdlib.h>

int *ip = malloc(sizeof(int));primitive types are always stack allocated. Use a wrapper class to store on the heap:
Integer i = new Integer(0);object i = 0;free primitive type on heapdelete i;#include <stdlib.h>

free(ip);garbage collectedgarbage collectedvalue of uninitialized primitive typessame as C. However, C++ provides a no-argument constructor for each primitive type which zero-initializes it.stack variables and heap variables allocated with malloc have indeterminate values. Global and static variables and heap variables allocated with calloc are zero-initialized.zero-initializedcompiler prevents use of uninitialized variables in some circumstances, and zero-initializes in othersboolean types
 boolBOOLbooleanboolsigned integer typessigned char 1+ byte
short int 2+ bytes
int 2+ bytes
long int 4+ bytes
long long int 4+ bytessigned char 1+ byte
short int 2+ bytes
int 2+ bytes
long int 4+ bytes
long long int 4+ bytesbyte 1 byte
short 2 bytes
int 4 bytes
long 8 bytessbyte 1 byte
short 2 bytes
int 4 bytes
long 8 bytesunsigned integer typesunsigned char: 8+
unsigned short int 2 bytes+
unsigned int 2 bytes+
unsigned long int 4+ bytes
unsigned long long int 4+ bytesunsigned char: 8+
unsigned short int 2 bytes+
unsigned int 2 bytes+
unsigned long int 4+ bytes
unsigned long long int 4+ byteschar 2 bytesbyte 1 byte
ushort 2 bytes
uint 4 bytes
ulong 8 bytesfloating point and decimal typesfloat
double
long doublefloat
double
long doublefloat 4 bytes
double 8 bytesfloat 4 bytes
double 8 bytes
decimal 12 bytestypedeftypedef int customer_id;
customer_id cid = 3;typedef int customer_id;
customer_id cid = 3;nonenoneenumenum day_of_week { mon, tue, wed, thu, fri, sat, sun };
day_of_week d = tue;enum day_of_week { mon, tue, wed, thu, fri, sat, sun };
enum day_of_week d = tue;public enum DayOfWeek { MON, TUE, WED, THU, FRI, SAT, SUN };
DayOfWeek d = DayOfWeek.TUE;public enum DayOfWeek { MON, TUE, WED, THU, FRI, SAT, SUN };
DayOfWeek d = DayOfWeek.TUE;arithmetic and logic c++objective cjavac#true and false
 true falseYES NOtrue falsetrue falsefalsehoods
 false 0 0.0 NULL0 0.0 NULLfalsefalselogical operators&& || !
and or not&& || !&& || !&& || !relational operators== != < > <= >=== != < > <= >=== != < > <= >=== != < > <= >=arithmetic operators
 + - * / %+ - * / %+ - * / %+ - * / %division by zeroprocess sent a SIGFPE signalprocess sent a SIGFPE signalthrows java.lang.ArithmeticExceptionthrows System.DivideByZeroExceptionpower#include <boost/math/special_functions.hpp>
boost::math::powm1<double>(2.0,3.0)+1#include <math.h>

pow(2.0,3.0);Math.pow(2.0,3.0);System.Math.Pow(2.0,3.0);absolute value#include <stdlib.h>

int i = -7;
abs(i);
#include <math.h>
float x = -7.77;
fabs(x)#include <stdlib.h>

int i = -7;
abs(i);
#include <math.h>
float x = -7.77;
fabs(x)Math.abs(-7)
Math.abs(-7.77)System.Math.Abs(-7)
System.Math.Abs(-7.77)transcendental functions#include <math.h>

sqrt exp log log2 log10 sin cos tan asin acos atan atan2#include <math.h>

sqrt exp log log2 log10 sin cos tan asin acos atan atan2Math.sqrt Math.exp Math.log none Math.log10 Math.sin Math.cos Math.tan Math.asin Math.acos Math.atan Math.atan2using System;
 
Math.Sqrt Math.Exp Math.Log none Math.Log10 Math.Sin Math.Cos Math.Tan Math.Asin Math.Acos Math.Atan Math.Atan2arithmetic truncation#include <math.h>
 
double d = 3.77;
 
long trunc = (long)d;
long rnd = round(d);
long flr = floorl(d);
long cl = ceill(d);#include <math.h>
 
double d = 3.77;
 
long trunc = (long)d;
long rnd = round(d);
long flr = floorl(d);
long cl = ceill(d);(long)3.77
Math.round(3.77)
(long)Math.floor(3.77)
(long)Math.ceil(3.77)using System;
 
(long)3.77
Math.Round(3.77)
Math.Floor(3.77)
Math.Ceiling(3.77)random integer#include <boost/random.hpp>
using namespace boost;
mt19937 rng;
uniform_int<> ui(0,RAND_MAX);
variate_generator<mt19937&, uniform_int<> > brand(rng, ui);
int i = brand()#include <stdlib.h>

int i = rand();java.util.Random r = new java.util.Random();
int i = r.nextInt();System.Random r = new System.Random();
int i = r.Next();bit operators<< >> & | ^ ~
bitand bitor comp<< >> & | ^ ~<< >> & | ^ ~<< >> & | ^ ~strings c++objective cjavac#type
 std::stringNSStringjava.lang.Stringstringliteral
 none@"hello""don't say\"no\"""hello"newline in literal?string literals can extend over multiple lines, but the newlines do not appear in the resulting stringstring literals can extend over multiple lines, but the newlines do not appear in the resulting stringnostring literals can extend over multiple lines, but the newlines do not appear in the resulting stringescapes
 \a \b \f \n \r \t \v \xhh \\ \" \' \o \oo \ooo\a \b \f \n \r \t \v \xhh \\ \" \' \o \oo \ooo\b \f \n \r \t \uhhhh \\ \" \' \o \oo \ooo\a \b \f \n \r \t \v \xhh \xhhhh \\ \" \' \o \oo \oooallocate stringstring *s = new string("hello");NSString *s = @"hello";String s = "hello";
String t = new String(s);string s = "hello";
string t = string.Copy(s);length
 s->length()[s length]s.length()s.Lengthcomparisonstring *s1 = new string("hello");
string *s2 = new stringt("world");
cout << s1->compare(*s2) << endl;[@"hello" compare:@"hello"]"hello".compareTo("world")"hello".CompareTo("world")semantics of ==value comparisonobject identity comparisonobject identity comparisonvalue comparisonto C string
 s->c_str()[s UTF8String]nonenonestring to number#include <sstream>
stringstream ss("7 14.3 12");
int i;
double d;
long l;
ss >> i >> d >> l;[@"14" integerValue]
[@"14" longLongvalue]
[@"14.7" floatValue]
[@"14.7" doubleValue]Byte.parseByte("14")
Short.parseShort("14")
Integer.parseInt("14")
Long.parseLong("14")
Float.parseFloat("14.7")
Double.parseDouble("14.7")byte.Parse("14")
short.Parse("14")
int.Parse("14")
long.Parse("14")
float.Parse("14")
double.Parse("14")
decimal.Parse("14")number to string  Integer.toString(14)
Long.toString(14)
Double.toString(14.7)14.ToString()
14.7.ToString()split#include <boost/algorithm/string.hpp>
#include <vector>
string s("Bob Amy Ned");
vector<string> vec;
boost::split(vec, s, boost::is_any_of(" "));[@"Bob Ned Amy" componentsSeparatedByString:@" "]"Bob Ned Amy".split(" ")string[] names = "Bob Ned Amy".Split(' ');join
    System.String.Join(", ", names)concatenatestring *s1 = new string("hello");
string *s2 = new string(" world");
cout << *s1 + *s2 << endl;NSString *s1 = @"hello";
NSString *s2 = @" world";
NSString *s3 = [s1 stringByAppendingString:s2];"hello" + " world""hello" + " world"substringstring("hello").substr(2,2)[@"hello" substringWithRange:NSMakeRange(2,2)]"hello".substring(2,4)"hello".Substring(2,2)index
 string("hello").find("ll")[@"hello" rangeOfString:@"ll"].location"hello".indexOf("ll")"hello".IndexOf("ll")sprintf#include <sstream>
ostringstream o('');
<< "Spain" << ": " << 7;
o.str();[NSString stringWithFormat:@"%@: %d", @"Spain", 7]String.format("%s: %d", "Spain", 7)string.Format("{0}: {1}", "Spain", 7)uppercase#include <boost/algorithm/string.hpp>
string s("hello");
boost::to_upper(s);[@"hello" uppercaseString]"hello".toUpperCase()"hello".ToUpper()lowercase#include <boost/algorithm/string.hpp>
string s("HELLO");
boost::to_upper(s);[@"HELLO" lowercaseString]"HELLO".toLowerCase()"HELLO".ToLower()trim#include <boost/algorithm/string.hpp>
string s(" hello ");
boost::trim(s);[@" hello " stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]]" hello ".trim()" hello ".Trim()pad on right [@"hello" stringByPaddingToLength:10 withString:@" " startingAtIndex:0]  regular expressions c++objective cjavac#regex match#include <boost/xpressive/xpressive.hpp>
using namespace boost::xpressive;
sregex re = sregex::compile(".*ll.*");
smatch matches;
string s("hello");
bool is_match = regex_match(s, matches, re);NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @".*ll.*"];
BOOL is_match = [pred evaluateWithObject:@"hello"];boolean isMatch = "hello".matches(".*ll.*");using System.Text.RegularExpressions;
Regex regex = new Regex("ll");
bool isMatch = regex.IsMatch("hello");regex substitute#include <boost/xpressive/xpressive.hpp>
using namespace boost::xpressive;
string s("hello");
sregex re1 = as_xpr("ll");
string format1("LL");
string result1 = regex_replace(s, re1, format1, regex_constants::format_first_only);
sregex re2 = as_xpr("l");
string format2("L");
string result2 = regex_replace(s, re2, format2); String s1 = "hello".replace("ll","LL");
String s2 = "hello".replaceAll("l","L");using System.Text.RegularExpressions;
Regex r1 = new Regex("ll");
String s1 = r1.Replace("hello", "LL", 1);
Regex r2 = new Regex("l");
String s2 = r2.Replace("hello", "L");dates and time c++objective cjavac#date/time type
   java.util.DateSystem.DateTimecurrent date/time  long millis = System.currentTimeMillis();
Date dt = new Date(millis);DateTime dt = DateTime.Now();to unix epoch, from unix epoch  long epoch = dt.getTimeInMillis()/1000;

Date dt2 = new Date(epoch * 1000);long hundredM = 100*1000*1000;
long sec = dt.ToFileTimeUtc() / hundredM;
long epoch = sec - 1164444480;

long ft = (epoch + 1164444480) * hundredM;
Date dt2 = DateTime.FromFiltTimeUtc(ft);strftime  String s = "yyyy-MM-dd HH:mm:ss";
DateFormat fmt = new SimpleDateFormat(s);
String s2 = fmt.format(dt);String s = "yyyy-MM-dd HH:mm:ss");
String s2 = dt.ToString(s);strptime  String s = "2011-05-03 17:00:00";
Date dt2 = fmt.parse(s);CultureInfo enUS =
  new CultureInfo("en-US");

DateTime dt2 = DateTime.ParseExact(
  "2011-05-03 17:00:00",
  "yyyy-MM-dd HH:mm:ss",
  enUS);arrays c++objective cjavac#allocate array on stackint a[10];int a[10];arrays must be allocated on heaparrays must be allocated on heapallocate array on heapint *a = new int[10];#include <stdlib.h>
int *a = calloc(10, sizeof(int));int[] a = new int[10];int[] a = new int[10];free array on heapdelete[] a;#include <stdlib.h>
free(a);garbage collectedgarbage collectedarray literalint a[] = {1,2,3};NSArray *a = [NSArray arrayWithObjects:@"hello", @"goodbye", nil];int[] a = {1,2,3};int[] a = {1,2,3};array access
 a[0][a objectAtIndex:0]a[0]a[0]length
 none[a count]a.lengtha.Lengtharray out-of-bounds resultundefined, possible SIGSEGVraises NSRangeException exceptionArrayIndexOutOfBoundsExceptionIndexOutOfRangeExceptionarray iterationint a[10];
for (i=0; i<10; i++ ) {
  do something with a[i]
}NSEnumerator *i = [a objectEnumerator];
id o;
while (o = [i nextObject]) {
  do something with o
}for (String name : names) {foreach (string name in names) {struct definitionclass MedalCount {
public:
  const char *country;
  int gold;
  int silver;
  int bronze;
};struct medal_count {
  const char* country;
  int gold;
  int silver;
  int bronze;
};public class MedalCount {
  public String country;
  public int gold;
  public int silver;
  public int bronze;
}public class MedalCount {
  public string country;
  public int gold;
  public int silver;
  public int bronze;
}struct declarationMedalCount spain;struct medal_count spain;MedalCount spain = new MedalCount();MedalCount spain = new MedalCount();struct initializationMedalCount spain = { "Spain", 3, 7, 4 };struct medal_count spain = { "Spain", 3, 7, 4};
struct medal_count france = { .gold = 8, .silver = 7, .bronze = 9, .country = "France" };no object literal syntax; define a constructorno object literal syntax; define a constructorstruct member assignmentspain.country = "Spain";
spain.gold = 3;
spain.silver = 7;
spain.bronze = 4;spain.country = "Spain";
spain.gold = 3;
spain.silver = 7;
spain.bronze = 4;spain.country = "Spain";
spain.gold = 3;
spain.silver = 7;
spain.bronze = 4;spain.country = "Spain";
spain.gold = 3;
spain.silver = 7;
spain.bronze = 4;struct member accessint spain_total = spain.gold + spain.silver + spain.bronze;int spain_total = spain.gold + spain.silver + spain.bronze;int spain_total = spain.gold + spain.silver + spain.bronze;int spain_total = spain.gold + spain.silver + spain.bronze;vector declaration#include <vector>
vector <int> vec;NSMutableArray *a = [NSMutableArray arrayWithCapacity:10];java.util.Vector<String> vec = new java.util.Vector<String>();using System.Collections.Generic;
List<string> l = new List<string>();vector pushvec.push_back(7);[a addObject:@"hello"];vec.add("hello");
or
vec.add(vec.size(), "hello")l.Add("hello");vector pop
 vec.pop_back();[a removeLastObject];vec.removeElementAt(vec.size()-1);l.RemoveAt(l.Count - 1);vector size
 vec.size()[a count]vec.size()l.Countvector accessvec[0]
vec.at(0)[a objectAtIndex:0]vec.elementAt(0)l[0]vector out of bounds resultvec[] has undefined behavior
vec.at() raises out_of_rangeraises NSRangeExceptionthrows ArrayIndexOutOfBoundsExceptionthrows System.ArgumentOutOfRangeExceptionvector iterationint sum = 0;
vector<int>::iterator vi;
for (vi = vec.begin(); vi != vec.end(); vi++ ) {
  sum += *vi;
}NSEnumerator *i = [a objectEnumerator];
id o;
while (o = [i nextObject]) {
  do something with o
}for ( String s : vec ) {
  do something with s
}foreach ( string s in l ) {
  do something with s
}dictionaries c++objective cjavac#pairpair<int, float> p(7, 3.14);
cout << p.first << ", " << p.second << endl;  using System.Collections.Generic;
KeyValuePair<string,int> pr = new KeyValuePair<string,int>("hello",5);
System.Console.WriteLine("{0} {1}", pr.Key, pr.Value);map declaration#include <map>
map<string, int> m;NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:10];java.util.TreeMap<String, Integer> m = new java.util.TreeMap<String, Integer>();using System.Collections.Generic;
Dictionary<string, int> dict = new Dictionary<string, int>();map accessm["hello"] = 5;
cout << m["hello"]) << endl;[dict setObject:@"5" forKey:@"hello"];
[dict objectForKey:@"hello"]m.put("hello", 5);
m.get("hello")dict.Add("hello", 5);
dict["hello"]map size
 m.size()[dict count]m.size()dict.Countmap remove elementm.erase(m.find("hello"));[dict removeObjectForKey:@"hello"];m.remove("hello");dict.Remove("hello");map element not found resultNULLNULLnullthrows KeyNotFoundException
in System.Collections.Genericmap iteratemap<string,int>::iterator mi;
for (mi = m.begin(); mi != m.end(); mi++) {
  printf("%s %d", mi->first, mi->second)
}NSEnumerator *i = [dict keyEnumerator];
id key;
while ((key = [i nextObject])) {
  do something with key
}for ( java.util.Map.Entry<String, Integer> e : m.entrySet() ) {
  use e.getKey() or e.getValue()
}foreach ( KeyValuePair<string,int> e in dict) {
  use e.Key and e.Value
}functions c++objective cjavac#pass by valuevoid use_integer(int i) {
  function body
}
int i = 7;
use_integer(i);void use_integer(int i) {
  function body
}
int i = 7;
use_integer(i);primitive types are always passed by valueprimitive types are always passed by valuepass by addressvoid use_iptr(int *i) {
  function body
}
int i = 7;
use_iptr(&i);void use_iptr(int *i) {
  function body
}
int i = 7;
use_iptr(&i);nonenonepass by referencevoid use_iref(int& i) {
printf("using iref: %d", i);
}
int i = 7;
use_iref(i);noneobjects and arrays are always passed by referenceobjects and arrays are always passed by referencedefault argument valuefloat log(float exp, float base=10.0) {noneuse method overloadinguse method overloadingnamed parametersnone+(float)weight: (float) w height: (float) h {
  return (w * 703) / (h * h);
}
+(float)height: (float) h weight: (float) w {
  return [BMI weight: w height: h];
}
[BMI weight:155 height:70];
[BMI height:70 weight:155];noneadded in C# 4.0:
static int BMI(int weight, int height) {
  return (weight * 703) / (height * height);
}
BMI(weight: 123, height: 64);
BMI(height: 64, weight: 123);function overloadingyesmethod overloading onlyyesyesvariable number of argumentsuse C; use default values or function overloading for finite number of aritiesuse C; use method overloading for finite aritiespublic static String concat(String first, String… rest) {
  StringBuilder sb = new StringBuilder(first);
  for (String arg: rest) {
    sb.append(arg);
  }
  return sb.toString();
}
String s = Concat.concat("Hello", ", ", "World", "!");public static string concat(params string[] args) {
  return System.String.Join("",args);
}
string s = Concat.concat("Hello", ", ", "World", "!")passing functions    anonymous function    operator overloadingRational Rational::operator+(Rational& o) {
  return Rational(this->num*o.denom + o.num*this->denom, this->denom * o.denom);
}nonenonepublic static Rational operator+(Rational a, Rational b) {
  return new Rational(a.num*b.denom + b.num *a.denom,a.denom*b.denom);
}execution control c++objective cjavac#forint i, n;
for (i=1,n=1; i<=10; i++) {
  n *= i;
}int i, n;
for (i=1,n=1; i<=10; i++) {
  n *= i;
}int n = 1;
for (int i=1; i<=10; i++) {
  n *= i;
}int i, n;
for (i=1,n=1; i<=10; i++) {
  n *= i;
}ifif (i>0) {
  signum = 1;
} else if (i==0) {
  signum = 0;
} else {
  signum = -1;
}if (i>0) {
  signum = 1;
} else if (i==0) {
  signum = 0;
} else {
  signum = -1;
}if (i>0) {
  signum = 1;
} else if (i==0) {
  signum = 0;
} else {
  signum = -1;
}if (i>0) {
  signum = 1;
} else if (i==0) {
  signum = 0;
} else {
  signum = -1;
}while|int i = 0;
while (i<10) {

  i++;
}|int i = 0;
while (i<10) {

  i++;
}int i = 0;
while (i<10) {

  i++;
}int i = 0;
while (i<10) {

  i++;
}switchswitch(i) {
case 0:
  0;
  break;
case 1:
  1;
  break;
default:
  -1;
  break;
}switch(i) {
case 0:
  0;
  break;
case 1:
  1;
  break;
default:
  -1;
  break;
}switch(i) {
case 0:
  0;
  break;
case 1:
  1;
  break;
default:
  -1;
  break;
}switch(i) {
case 0:
  0;
  break;
case 1:
  1;
  break;
default:
  -1;
  break;
}throw exceptionthrow exception();NSException *exc = [NSException exceptionWithName:@"error" reason:@"failed" userInfo:nil];
@throw exc;throw new Exception("failed");throw new System.Exception("failed");catch exceptiontry {
  throw exception();
} catch (exception& e) {
  cout << "failed" << endl;
}@try {
  [NSException raise:@"error" format:@"failed"];
} @catch (NSException *e) {
  printf([[e reason] UTF8String]);
}try {
  throw new Exception("failed");
} catch (Exception e) {
  System.out.println(e.getMessage());
}try {
  throw new System.Exception("failed");
} catch (System.Exception e) {
  System.Console.WriteLine(e.Message);
}finally clauseuse local object with destructor@try {
  risky code
} @finally {
  perform cleanup
}try {
  risky code
} finally {
  perform cleanup
}try {
  risky code
} finally {
  perform cleanup
}methods must declare exceptionsnonoyesnofiles c++objective cjavac#read from file#include <fstream>
string line;
ifstream f("/etc/passwd");
if (f.is_open()) {
  while (!f.eof()) {
    getline(f, line);
    process line
  }
  f.close();
  if ( 0 != f.fail() ) {
    handle error
  }
}
else {
  handle error
}NSError *error = nil;
NSString *s = [NSString stringWithContentsOfFile: @"/etc/passwd" encoding:NSUTF8StringEncoding error:&error];
if ( error != nil ) {
  handle error
}
NSArray *a = [s componentsSeparatedByString:@"\n"];
id line;
while (line = [i nextObject]) {
  process line
}import java.io.BufferedReader;
import java.io.FileReader;
BufferedReader in = new BufferedReader(new FileReader("/etc/passwd"));
String line;
while ((line = in.readLine()) != null) {
  process line
}using System.IO;
StreamReader sr = new StreamReader("/etc/passwd");
string line;
while ((line = sr.ReadLine()) != null) {
  use line
}write to file#include <fstream>
ofstream f("/tmp/test4");
int i;
for (i=0; i<10; i++) {
  << i << endl;
}
f.close();
if (0 != f.fail()) {
  handle error
} import java.io.BufferedWriter;
import java.io.FileWriter;
BufferedWriter fout = new BufferedWriter(new FileWriter("/tmp/test2"));
int i;
for (i=0; i<10; i++) {
  fout.write(String.format("%d", i));
  fout.newLine();
}
fout.close();using System.IO;
StreamWriter fout = new StreamWriter("/tmp/test3");
int i;
for (i=0; i<10; i++) {
  fout.WriteLine(i.ToString());
}
fout.Close();directories c++objective cjavac#processes and environment c++objective cjavac#signature of mainint main(int argc, char **argv) {int main(int argc, char **argv) {public class Foo {
  public static void main(String[] args) {public class Foo {
  public static void Main(string[] args) {first argument
 pathname of executablepathname of executablefirst command line argumentfirst command line argumentenvironment variable#include <stdlib.h>
char *home = getenv("HOME");
setenv("EDITOR", "emacs", 1);
unsetenv("EDITOR");NSString *home = [[[NSProcessInfo processInfo] environment] objectForKey:@"HOME"];String home = System.getenv("HOME");using System.Environment;
string home = GetEnvironmentVariable("HOME");
SetEnvironmentVariable("EDITOR", "emacs");
SetEnvironmentVariable("EDITOR", null);iterate thru environment variables NSEnumerator *i = [[[NSProcessInfo processInfo] environment] keyEnumerator];
id key;
while ((key = [i nextObject])) {
  use NSString key
}import java.util.Map;
Map<String, String> env = System.getenv();
for (String name : env.keySet()) {
  String value = env.get(name));
}using System.Collections;
using System.Environment;
IDictionary env = GetEnvironmentVariables();
foreach (DictionaryEntry de in env) {
  use de.Key or de.Value
}libraries and namespaces c++objective cjavac#declare namespacenamespace foo {
  namespace bar {
    class Baz {
      static const int ANSWER = 42;
    };
  }
} package foo.bar;
public class Baz {
  public static final int ANSWER = 42;
}namespace foo {
  namespace bar {
    public class Baz {
      public const int ANSWER = 42;
    };
  }
}multiple namespaces per fileyes noyesnamespaces map to directoriesno yesnoimport namespaceusing namespace foo::bar;
cout << Baz::ANSWER << endl; import foo.bar.*;
System.out.println(Baz.ANSWER);using foo.bar;
System.Console.WriteLine(Baz.ANSWER);import part of namespaceusing namespace foo;
cout << bar::Baz::ANSWER << endl; nonenoneimport symbolusing foo::bar::Baz;
cout << Baz::ANSWER << endl; import foo.bar.Baz;
System.out.println(Baz.ANSWER);noneimport static symbolnone import static foo.bar.Baz.ANSWER;
System.out.println(ANSWER);noneimport position
 anywhere a statement is legal after package and before type definitionsoutside of class definitionsusing a symbol that hasn't been importedcout << foo::bar::Baz::ANSWER << endl; System.out.println(foo.bar.Baz.ANSWER);using System.Console;
WriteLine(foo.bar.Baz.ANSWER);objects c++objective cjavac#define classRational.hpp:
class Rational {
 public:
  int num, denom;
  Rational(int num, int denom);
  virtual ~Rational();
  Rational operator+(Rational& addend);
  static Rational max(Rational& a, Rational& b);
};Rational.h:
#import <Foundation/Foundation.h>
@interface Rational : NSObject {
  int num;
  int denom;
}
@property int num, denom;
-(Rational*) initWith: (int) n: (int) d;
-(Rational*) add: (Rational *) o;
@end
Rational.m:
#include "Rational.h"
@implementation Rational
@synthesize num, denom;
-(Rational*) add: (Rational*) o {
  int sum_n = self.num * o.denom + o.num * self.denom;
  int sum_d = self.denom * o.denom;
  Rational* sum = [[Rational alloc] initWith: sum_n: sum_d];
  return sum;
}
@endpublic class Rational {
  public int num;
  public int denom;
  public Rational add(Rational o) throws Exception {
    return new Rational(this.num*o.denom + o.num*this.denom,this.denom*o.denom);
  }
  public static Rational max(Rational a, Rational b) {
    return (a.num*b.denom > a.num*b.denom) ? a : b;
  }
}public class Rational {
  public int num;
  public int denom;
}class definition locationtop level, class block, or function blocktop leveltop level, class block, or function block for anonymous classes constructorRational::Rational(int n, int d) : num(n), denom(d) {
  if (denom == 0) {
    throw "zero denominator";
  }
  int div = gcd(n,d);
  num = num / div;
  denom = denom / div;
}-(Rational*) initWith: (int) n: (int) d {
  self = [super init];
  if (self) {
    self.num = n;
    self.denom = d;
  }
  return self;
}public Rational(int n, int d) throws Exception {
  if (d == 0) {
    throw new Exception("zero denominator");
  }
  if ( d < 0 ) {
    this.num = -1 * n;
    this.denom = -1 * d;
  }
  else {
    this.num = n;
    this.denom = d;
  }
}public Rational(int n, int d) {
  if (0 == d) {
    throw new System.Exception("zero denominator");
  }
  if (d < 0) {
    this.num = -1 * n;
    this.denom = -1 * d;
  }
  else {
    this.num = n;
    this.denom = d;
  }
}create objectRational r1(7,3);
Rational *r2 = new Rational(8,5);Rational *r = [[Rational alloc] initWith: 7: 3];Rational r = new Rational(7,3);Rational r = new Rational(7,3);destructorRational::~Rational() {};-(void) dealloc {
  [super dealloc];
  printf("deallocated…");
}protected void finalize() throws Throwable {
  super.finalize();
}~Rational() {
  perform cleanup
}destroy object
 delete r2;[r release];nonenonedefine methodint Rational::height() {
  return (abs(num) > abs(denom)) ? abs(num) : abs(denom);
}-(int) height {
  if ( abs(self.num) > abs(self.denom) ) {
    return abs(self.num);
  }
  return abs(self.denom);
}public int height() {
  return (Math.abs(this.num) > this.denom) ? Math.abs(this.num) : this.denom;
}public int Height() {
  return (System.Math.Abs(this.num) > this.denom) ? System.Math.Abs(this.num) : this.denom;
}invoke methodr1.height();
r2->height();[r1 height];r.height();r.Height();dynamic dispatchdeclare as virtual in base classdispatch always dynamicdispatch dynamic by defaultdeclare as virtual in base class and override in derived classstatic dispatchdispatch static by defaultdispatch always dynamicdeclare as final, private, or static (i.e. make it a class method)dispatch static by default; compiler error if same method defined in base and derived class and not marked virtual in base classdefine class methoddeclare static in class definitionprecede definition with +:
+(Rational*) max: (Rational*) a: (Rational*) b {
  if ( a.num * b.denom > b.num * a.denom ) {
    return a;
  }
  return b;
}declare static in class definitiondeclare static in class definitioninvoke class method    name of receiverthisselfthisthisaccess controlaccess keywords define regions:
class Foo {
  int privateInt1;
  int privateInt2;
public:
  int publicInt1;
  int publicInt2;
protected:
  int protectedInt1;
  int protectedInt2;
private:
  int privateInt3;
  int privateInt4;
};access keywords define regions:
@interface Foo : NSObject {
  int protectedInt1;
  int protectedInt2;
@public
  int publicInt1;
  int publicInt2;
@protected
  int protectedInt3;
  int protectedInt4;
@private
  int privateInt1;
  int privateInt2;
}
@endaccess keywords required for methods and members:
public class Foo {
  private int privateInt;
  protected int protectedInt;
  public int publicInt;
}access keywords available for methods and members:
public class Foo {
  private int privateInt1;
  int privateInt2;
  protected int protectedInt;
  public int publicInt;
}anonymous classpossible but not usefulnone(new Object() { public void hello() { System.out.println("hello!"); } }).hello(); subclassclass Integer : public Rational {
 public:
  Integer(int n);
  virtual ~Integer();
}; public class RInteger extends Rational {
  public RInteger(int n) throws Throwable {
    super(n, 1);
  }
} invoking superclass constructorInteger::Integer(int n) : Rational(n, 1) {
} super(n, 1); mark class underivable or method unoverrideablenonenonefinalsealedroot class
 noneNSObjectjava.lang.ObjectSystem.Objectroot class methodsnoneautorelease
class
conformsToProtocol:
hash
isEqual:
isKindOfClass:
isProxy
performSelector:
performSelector:withObject:
performSelector:withObject:withObject:
release
respondsToSelector:
retain
retainCount
self
superclassclone()
equals()
finalize()
getClass()
hashCode()
toString()Equals()
Finalize()
GetHashCode()
GetType()
MemberwiseClone()
ReferenceEquals()
ToString()generic types c++objective cjavac#define generic typetemplate <class A>
class Foo {
public:
  A a;
  Foo(A a);
};
 
template <class A>
Foo<A>::Foo(A a) : a(a) {
} public class Foo<A> {
  public A a;
  public Foo(A a) {
    this.a = a;
  }
}public class Foo<A> {
  public A a;
  public Foo(A a) {
    this.a = a;
  }
}instatiate generic typeFoo<string> f = Foo<string>("foo"); Foo<String> f = new Foo<String>("foo");Foo<string> f = new Foo<string>("foo");generic functiontemplate <class C>
C add(C a, C b) {
  return a + b;
}   generic arraytemplate <class C>
class Foo {
public:
  C a[10];
}; not permitted. Use Object as the element type for the array or use an ArrayList.public class Bar<C> {
  public C[] a;
  public Bar(C c) {
    this.a = new C[10];
  }
}value parametertemplate <int N>
int add(int i) {
  return N+i;
}
 
cout << add<7>(3) << endl;   template parameter    template specialization    multiple type parameterstemplate <class A, class B>
class Pair {
public:
  A a;
  B b;
  Pair(A a, B b);
};
 
template <class A, class B>
Pair<A, B>::Pair(A a, B b) :
  a(a), b(b) { }
  
Pair<int, string> p =
  Pair<int, string>(7, "foo");   generic type parametersPair<int, Foo<string> > p =
  Pair<int, Foo<string> >(
    7, Foo<string>("foo"));   template parameters    reflection c++objective cjavac#get type class of object  o = new Object();
Class c = o.getClass();object o = new object();
System.Type t = o.GetType();
or
System.type t = typeof(o);get type class from string  Class c = Class.forName("java.io.File");using System;
Type t = Type.GetType("object");get type class from type identifiertypeid(Foo)  System.Type t = typeof(object);class name
 typeid(Foo).name() String name = c.getName();t.ToString();get methods  import java.lang.reflect.*;
Method[] m = c.getMethods();using System.Reflection;
System.Type t = typeof(object);
MethodInfo[] a = t.GetMethods();has method  import java.lang.reflect.*;
Class c = Class.forName("java.io.File");
Method[] a = c.getMethods();
boolean hasMethod = false;
for (int i=0; i < a.length; i++) {
  if (a[i].getName() == "toString") {
    hasMethod = true;
  }
}null if method not found://
MethodInfo m = t.GetMethod("ToString");invoke method object  import java.lang.reflect.*;
Class c = Class.forName("java.io.File");
Method m = c.getMethod("toString");
Object o = new Object();
m.invoke(o);m.Invoke(o);web c++objective cjavac#url encode/decode  import java.net.URLEncoder;
import java.net.URLDecoder;

String url = "http://www.google.com";
String s = URLEncoder.encode(url, "utf8");
String s2 = URLDecoder.decode(s, "utf8");  ________________________________________________________________________________________________________________________________________________________________________________________________

General Footnotes

hello world

How to write, compile, and run a "Hello, World!" program.

version used

The compiler version used for this cheatsheat.

version

How to get the compiler version.

libraries used

The libraries used for this reference sheet.

C

C Standard Library
GNU C Library

The C standard library evolved with Unix and was first standardized by POSIX in 1988. It is a collection of header files and compiled library objects, and it is available on most systems including Windows. The headers must be specified in the source files, but it is not necessary to explicitly link to the library, at least when using gcc.

C++

Standard Template Library (STL)
Boost 1.42.0

The STL provides a string class, streams, and a good selection of generic container classes. Most systems provide it, though it may not be installed by default. The Boost library fills out the C++ development environment, providing a lot of functionality that is available to java via the Java API. Boost generally has to be downloaded and installed separately.

Objective C

Foundation Framework

The Foundation Framework is the core of Cocoa, a set of libraries for Objective C development on Mac OS X and the iPhone. The Foundation Framework descends from NextStep, hence the NS prefix in the class names. NextStep was made available to operating systems other than Next as OpenStep and the GNU implementation is called GNUStep.

Java

Java 1.6 API

Java comes with a large standard library called the Java API.

C#

.NET Framework 4 Class Library
Mono Documentation

The core of the .NET framework is called the Base Class Library. Mono implements the BCL, but does not implement all of the .NET framework.

source, header, and object file suffix

c++

The gcc compiler will treat a file with any of the following suffixes as C++ source:

const int NULL = 0;

printf

How to print a formatted string to standard out.

case and underscores in names

Conventions typically observed for use of case and underscores in names. These conventions are not enforced by the compiler.

C++

C++ naming conventions vary widely. The naming conventions cited here are taken from the Google C++ Style Guide.

coalesce

The equivalent of the COALESCE function from SQL.

C, C++, Objective C++:

The short circuit or operator || can be used as a coalesce operator. However, in C, C++, and Objective C, NULL is identical to zero, whereas in databases they are two distinct values.

Java:

The ternary operator provides the closest approximation to COALESCE, but it does not have the same behavior if the tested value has a side effect.

Primitive Types Footnotes

declare primitive type on stack

How to declare a primitive type on the stack.

allocate primitive type on heap

How to allocate memory for a primitive type on the heap.

c++

new and delete can be used to manage the memory of both primitive types and objects.

objective c

Object C has a different memory management schemes for primitive types and objects. Objects are allocated with alloc and freed by means ofNSAutoreleasePool. For primitive types the same techniques are used as for C. However, idiomatic Objective C will declare primitive types as local variables or as part of the state of an object and avoid explicit calls to malloc.

Arrays of objects can be created with NSArray and NSMutableArray.

java

In Java, arrays are always stored on the heap and the JVM is responsible for garbage collection. The primitive types are stored (1) on the local frame, (2) as part of the state of an object, or (3) as part of the state of a class. The primitive types are never stored in the heap directly and when they are part of object state they are garbage collected with the object. Primitive types are passed by value unless they are encapsulated in an object.

Each of the primitive types has a wrapper class, and instantiating this class is the best approximation in Java to allocating the primitive type on the heap:

typedef signed char BOOL;#define YES (BOOL)1#define NO (BOOL)0

C#

bool is an alias for System.Boolean

signed integer types

C

Whether char is a signed or unsigned type depends on the implementation.

C#

C# has the following aliases:

sbyte: System.SByte
short: System.Int16
int: System.Int32
long: System.Int64

unsigned integer types

C

Whether char is a signed or unsigned type depends on the implmentation.

C#

C# has the following aliases:

byte: System.Byte
ushort: System.UInt16
uint: System.UInt32
ulong: System.UInt64

floating point and decimal types

C#

C# has the following aliases:

float: System.Single
double: System.Double
decimal: System.Decimal

typedef

C

Because C integer types don't have well defined sizes, typedef is sometimes employed to as an aid to writing portable code. One might include the following in a header file:

typedef enum { mon, tue, wed, thu, fri, sat, sun } day_of_week;day_of_week d = tue;

From the point of view of the C compiler, an enum is an int. The C compiler does not prevent assigning values to an enum type that are not in the enumerated list. Thus, the following code compiles:

main.cpp: In function ‘int main()’:main.cpp:21: error: invalid conversion from ‘int’ to ‘main()::day_of_week’

Java

Java added enums in 1.5.

Java enums are strongly typed like C++ enums. Unlike C++ enums, it is an error to use an enum value in an integer context. The value has a method ordinal()which returns the integer value, however.

When used in a string context, an enum will evaluate as the string corresponding to its identifier: i.e. "TUE" for DayOfWeek.TUE. This string can be accessed explicitly with DayOfWeek.TUE.toString(). Conversely, DayOfWeek.valueOf("TUE") returns DayofWeek.TUE.

Java enums are subclasses of java.lang.Enum. In particular, an enum is a class, and if the last value if the enum definition is followed by a semicolon, what follows is a class body which can contain methods and constructors. An enum class is final and cannot be subclassed, but an enum can implement an interface.

C#

Like Java enums, C# enums will return the string corresponding to their identifier. Unlike Java enums, C# enums will evaluate as integers in a numeric context.

When used as an argument in a C# style format string, an enum value returns the string corresponding to its identifier.

Arithmetic and Logic Footnotes

true and false

Literals for the boolean values true and false.

C

The following definitions are common:

String t = new String(s);

creates a copy of the string s. However, because Java strings are immutable, it would be safe to store the same string object it t as follows:

doublestrtod(const char *str, char **endp);

Java

parseInt has an optional second argument for the base.

number to string

split

join

java:

Use StringBuilder to implement join:

<code style="" font-family:'andale="" "="">public static String join(String[] a, String sep) {    StringBuilder sb = new StringBuilder();    for (int i=0; i<a.length; i++) {        if (i > 0) {            sb.append(sep);        }        sb.append(a[i]);    }    return sb.toString();}

concatenate

substring

index

sprintf

uppercase

lowercase

trim

pad

Regular Expressions

regex match

C

regcomp returns a non-zero value if it fails. The value can be inspected for a precise error reason; see the regcomp man page.

REG_EXTENDED is a bit flag which indicates that modern regular expressions are being used. Other useful flags are

  • REG_NOSUB: don't save string matched by regular expression
  • REG_NEWLINE: make ^ and $ match newlines in string
  • REG_ICASE: perform case insensitive matching

regex substitute

Date and Time Footnotes

date/time type

The data type used to store a combined date and time. The combination of date and time is also called a timestamp.

current date/time

How to get the current date and time.

to unix epoch, from unix epoch

How to convert a date/time object to the Unix epoch. How to convert the Unix epoch to a date/time object.

The Unix epoch is the number of seconds since 1 January 1970 UTC.

c#:

Windows file time is the number of nanoseconds since 1 January 1601 UTC divided by 100. The concept was introduced when journaling was added to NTFS with Windows 2000.

The magic constant (1164444480) used for the conversion can be calculated with the following code:

int a[] = {3,7,4,8,5,9,6,10};int x = a[4];int y = *(a+4);

array out-of-bounds result

array iteration

C

C arrays do not store their size, so C developers normally store this information in a separate variable. Another option is to use a special value to mark the end of the array:

struct medal_count {char* country;int gold;int silver;int bronze;}struct medal_count spain = { "Spain", 3, 7 4 };struct medal_count *winner = &spain;printf("The winner is %s with %d gold medals", (*winner).country, (*winner).gold);

ptr->mem is a shortcut for (*ptr).mem:

string *s = concat("Hello", ", ", "World", "!", NULL);

passing functions

anonymous function

operator overloading

Execution Control Footnotes

for

if

For all five languages, the curly braces surrounding an if or else clause are optional if the clause contains a single statement. All five languages resolve resulting dangling else ambiguity by setting the value of c to 2 in the following code:

Class Finally {  void (*finally)();  Finally(void (*f)()) : finally(f) {  }  ~Finally() {    do_cleanup();  }};{  Cleanup c();  risky();}

methods must declare exceptions

Java

If a method throws a subclass of java.lang.Exception, it must declare the exception in its throws clause. This includes exceptions originating in code called by the method. On the other hand, if the method throws a subclass of java.lang.Error, no declaration in the throws clause is necessary.

File Footnotes

read from file

C

If there is an error, the global variable errno will be set to a nonzero value, and strerror(errno) will return an error message for the error.

write to file

Directory Footnotes

Processes and Environment Footnotes

signature of main

first argument

C

The first argument is the pathname to the executable. Whether the pathname is absolute or relative depends on how the executable was invoked. If the executable was invoked via a symlink, then the first argument is the pathname of the symlink, not the executable the symlink points to.

environment variable

iterate thru environment variables

Library and Namespace Footnotes

Object Footnotes

define class

constructor

create object

destructor

C++

The C++ compiler will normally see to it that the destructor for a class and all its superclasses is called. The compiler may not be aware of the true class of the object if it was upcast to one of its base class. If the destructor was not declared virtual, then the derived class destructor and any other base class constructors will not get called. Thus many developers declare all destructors virtual.

Java

Java does not chain finalize() methods, so the derived class should explicitly call the parent.

destroy object

Java

finalize() is called by the Java garbage collector.

define method

invoke method

dynamic dispatch

static dispatch

Method dispatch is static if the method is determined by the variable type, and dynamic if it is determined by the value type. These techniques of method dispatch yield different results when both the base class and the derived class have implementations for a method, and an instance of the derived class is being stored in a variable with type of the base class.

When dispatch is static, the compiler can determine the code that will be executed for the method call. When dispatch is dynamic, the code that will be executed is a runtime decision. C++ implementations usually achieve this by storing function pointers in the object: qv virtual method table.

The use of the keyword static in the declaration of a class method in C++, Java, and C# is perhaps unfortunate. Class methods are always statically dispatched, so the concepts are not unrelated.

define class method

invoke class method

name of receiver

access control

objective c:

Access control only applies to members; all methods are public. gcc 4.0 does not enforce the access restrictions; it merely gives warnings.

anonymous class

subclass

superclass constructor

mark class underivable or method overrideable

root class

Name of the root class, if there is one.

objective c:

It is possible to define a root class other than NSObject.

root class methods

A selection of methods available on the root class.

Generic Type Footnotes

define generic type

instantiate generic type

Reflection Footnotes

get type class of object

get type class from string

get type class from type identifier

c++:

typeid returns a value of type type_info. The assignment method and copy constructor of type_info are private.

class name

*c++:**

The string returned by type_info.name() contains more than the class name. The code below displayed the string "Z4mainE3Foo" when run on my system.

<code style="" font-family:'andale="" "="">class Foo {  int i;};puts(typeid(Foo).name());

get methods

has method

invoke method object

Web Footnotes

url encode/decode

How to URL encode and URL decode a string.

URL encoding is also called percent encoding. It is used to escape special characters in GET query string parameters.

Reserved characters according to RFC 3986 are replaced by a percent sign % followed by a two hex digit representation of the ASCII code. The reserved characters are:

<code style="" font-family:'andale="" "="">! * ' ( ) ; : @ & = + $ , / ? # [ ]

Spaces can optionally be represented by a plus sign +.

C

ANSI C Standard 1990
ANSI C Standard (pdf) 1999
C Standard Library
POSIX Library C Headers
Linux System Call Man Pages
Linux Subroutine Man Pages

C++

ISO C++ Standard 1998
C++0x (pdf) proposed standard as of 2010
STL
Boost 1.42

Objective C

Objective C 2.0 (pdf) Apple
GNUstep
Mac OS X Foundation Framework

Java

Java 1.6 API
Java 1.7 Project
JVM Specification 2nd Ed
The Java Language Specification 3rd Ed

C#

C# Standard: ECMA-334
Mono API
C# Programming Guide Microsoft

History

  • The C Family of Programming Languages
  • High Level Languages
  • Structured Languages
  • C
  • C++
  • Objective C
  • Java
  • C#

The C Family of Programming Languages

Early History of High Level Languages

Short Code
Fortran

Programming in the native machine language of a computer generally involves moving data into specific registers so that an arithmetic operation can be performed on it. Short Code was the first language which hid register details from the programmer; implemented in 1950 on the Univac I, it was an interpreted language which ran about 1/50th the speed of machine code.

John Backus proposed development of a compiled, high level language at IBM in 1953. The group which formed to implement the compiler had the ambition of making the generated code comparable in performance to machine code created by hand. The language was known as The IBM Mathematical Formula Translating System by 1954, and as Fortran by 1956. The compiler was available on the IBM 704 by 1957. Its speed relative to hand crafted machine code could be debated, but because it reduced the size of the source code by a factor of 20 it was an immediate success.

Early History of Structured Languages

The Syntax and Semantics of the Proposed International Algebraic Language of the Zurich ACM-GAMM Conference Backus 1959
Revised Report on the Algorithm Language Algol 60 Naur 1960
The Main Features of CPL Strachey 1963

Backus met with a group computer scientists in Zürich in 1958 to design a new language which would make it easier to write large programs. Large Fortran programs were intractable, in part because all variables were global in scope. Backus introduced a notation to describe the grammar of the new language that would eventually be known as Backus-Naur form.

Features of Algol that are relevant to C are: procedures with local scope, if and else with the dangling else ambiguity, for loops, the numeric types integer andreal, and a pointer keyword.

Christopher Strachey and others in the UK designed the language CPL in 1963, which is a heavyweight extension to Algol 60. Because of the complexity of the language, it was not implemented until 1970 and it was never widely used.

C History

BCPL Reference Manual (pdf) 1967
The Development of the C Language

A stripped down language called Basic CPL or BCPL was implemented by Martin Richards in 1967 on the IBM 7094. Instead of the begin and end keywords of Algol, BCPL uses curly brackets {} to delimit blocks; $( and $) were substituted when those characters were unavailable. BCPL has a single type called word. It used the // style comments that would re-appear in C++. Local variables were declared with let.

Ken Thompson stripped even more features from BCPL to fit the language onto a PDP-7 with 8k of memory and called the result B. After the PDP-7 implementation in 1969 the language was ported to the PDP-11 in 1970. It was used to implement an early version of Unix, which was originally written in PDP-7 assembler. B did not support nested procedures like its predecessor. Also it switched to = instead of := for assignment. Variables could be declared auto orstatic. B also introduced the ++ and -- incrementor and decrementor, which could be used in prefix and postfix position with correspondingly different semantics. Lastly, B introduced semicolons as statement terminators.

Dennis Ritchie took over maintenance of the B compiler in 1970 and the outcome of his work was the language C in 1972. C introduced the types int and char, which were considered necessary on the PDP-11. In 1973 the struct was added, which was like the record of Algol-W and Pascal. The /* */ style comment was derived from PL/I. The && and || operators were introduced with short-cut semantics.

The goal of both B and C was a language suitable for the implementation of Unix. Unix was a less ambitious operating system than its predecessor Multics, but it still delivered on many of the novel ideas of Multics. In particular Unix had processes, a file system which organized files in a directory tree, a command interpreter for the user, simple text files, and generic device access. Multics was implemented in the higher level language PL/I. Thompson and Ritchie wanted to stay above the level of assembler when implementing Unix, but they needed a simpler language than PL/I or even BCPL.

After 1973 C evolved by adding types. In 1977 changes were made in the interest of portability. In 1978 Kernighan and Ritchie published The C Programming Language, which became the standard for the language, though it did not mention additions such as void and enum that were soon added to the language. The language was standardized by ANSI in 1989, and this became an ISO standard in 1990. The 2nd edition of The C Programming Language published in 1988 describes ANSI C.

C spread in popularity during the 1980s with Unix. Pascal is a comparable language to C with what some regard as a cleaner design. However, the reasons for the eventual success of C over Pascal were already foreseen in a article by Kernighan in 1981. Lattice C produced a C compiler for DOS in 1982, and Microsoft licensed and distributed this product. The Windows API introduced in 1985 was written in C.

C++ History

A History of C++: 1979-1991 (pdf) Stroustrup

The core concepts of object oriented languages first appeared in Simula, a language developed by Kristen Nygaard and Ole-Johan Dahl. It was described in the 1962 paper 'SIMULA' An Extension of ALGOL to the Description of Discrete-Event Networks, and it was intended to be an environment for solving queuing problems via simulation. Simula as originally implemented (Simula I) was a preprocessor to Algol 60 on the UNIVAC 1107, and this version was ported to the Burroughs B5500 in 1968. The manual for Simula I appeared in 1965.

Dahl and Nygaard were not satisfied with the original version of Simula and decided to extend it to a general purpose language. They drew inspiration from Algol W (1965) by Wirth and Hoare, who introduced the user-defined record data type which would become the foundation of a class.

Simula 67 was formally defined and presented at a conference that year. The language introduced objects, classes, subclasses, virtual methods, dynamic binding, and coroutines. Like its predecessor it is a superset of Algol 60. Simula 67 implementations compiled directly to machine code, and became commercially available in the early 1970s.

As C became widespread in the 1980s, the idea of creating an object-oriented extension of it presented itself. C++ is a Simula inspired extension of C; the methods that an object will respond to are known at compile time. Type safety is a design goal of C++, and the language replaces C features such as macros and casts with type-safe alternatives.

Stroustrup started working on C with classes in 1979, and the language was renamed C++ in 1983. Stroustrup's book The C++ Language was published in 1985, and it was effectively the language definition. The 2nd edition of the book in 1989 introduced templates, namespaces, and exceptions. Borland introduced a C++ compiler for MS-DOS in 1991, and the Microsoft C compiler and gcc added support for C++ in 1992. C++ became an ISO standard in 1998.

Alexander Stepanov started working on what he called generic programming in 1979. An Ada library for generic list processing was available in 1987. A draft proposal for the Standard Template Library (STL), a generic programming library for C++, was made in 1994, and HP made an implementation freely available that year.

The Boost library was started around 1998. Version 1.10.3 was available in 1999.

As of March 2010 work is underway for a new version of C++ called C++0x.

Objective C History

Objective C is an object oriented extension of C based on Smalltalk instead of Simula: unlike C++ the methods—in Smalltalk and Objective C parlance the messages—an object will respond to are not known at compile time.

Smalltalk was designed by Alan Kay, with early versions implemented by Dan Ingalls. Smalltalk-71 was a simple implementation that introduced message passing. Smalltalk-72 introduced the Actor model. Smalltalk-76 borrowed the notion of classes from Simula and introduced a development environment with a GUI class/code browser. Smalltalk-80 introduced metaclasses (i.e. made classes themselves objects). Smalltalk-80 was also the first version of the language publicly available outside of PARC.

Objective C was developed by Brad Cox and Tom Love, and they published a description in 1986. NeXT licensed the language in 1988, and it became the primary language of the NeXT platform. The NeXT development tools, including Objective C, were made available to other platforms as OpenSTEP in 1993. Also, GNU versions of Objective C became available around that time.

With Mac OS X (2002) Apple provided two APIs, the Objective-C based Cocoa API which drew heavily on OpenSTEP and the C based Carbon API. The latter existed to make it easier to port older applications to Mac OS X. Apple came out with Objective C 2.0 in 2007 with Mac OS X 10.5. The iPhone also relies heavily on Objective C for development; its success has increased adoption of the language.

Java History

Java Version History

Java was developed by James Gosling at Sun and made publicly available in 1996. It is a compiled, objected oriented language with syntax similar to C++. It is perhaps best understood by how it differs from C++:

  • usually compiled to bytecode that runs on a VM
  • no separate source and header files; javadoc tool can extract method signatures from source
  • garbage collection
  • interfaces instead of multiple inheritance
  • no operator overloading

Compared to C++, the language is easier to use and easier to port. Applets that ran in the browser were an early use of the language that helped popularize it.

Version 1.1 (1997) added RMI and several types of nested classes including anonymous classes. Version 1.2 (1998) added the ability to reflect on the methods of a class or object at runtime. Version 1.4 (2002) added Perl style regular expressions. Version 1.5 (2004) added generics, which are roughly similar to C++ templates, and autoboxing, in which the compiler automatically wraps a primitive type with an instance of a wrapper class when needed.

Over the years Java has developed an extensive standard library; as of version 1.5 the standard library contains 3000 classes. Third parties are encouraged to use their internet domain name to determine the location of their code in the Java code namespace, a technique which makes it easy to integrate code from non-standard sources.

Other languages have targeted the JVM: Jython since 1997, Scala and Groovy since 2003, and Clojure since 2007. JVM languages include interpreters written in Java and languages which can be compiled to bytecode.

C# History

Soon after its release Java was licensed by Microsoft which released its own JVM and an associated IDE called Visual J++. Sun sued Microsoft for introducing incompatibilities in their implementation and Microsoft ultimately abandoned Java, opting instead to develop a new, Java-like language called C#. Anders Hejlsberg, known for his work on Delphi at Borland, was a lead architect for the new language.

Java TerminologyC#/.NET TerminologyJavaC#Java bytecodeCommon Intermediate Language (CIL)JVMVirtual Execution System (VES)Java API.NET FrameworkJava VM SpecificationCommon Language Infrastructure (CLI)

The CLI was standardized as ECMA-335 in 2003. Microsoft's own VES is called the Common Language Runtime (CLR), though sometimes CLR is used as a generic term for any VES. The Microsoft CLR only runs on Windows but Mono is an open source VES available on Linux and Mac.

原创粉丝点击