C++ Style Languages: C++, Objective C, Java, C#

a side-by-side reference sheet

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.2 gcc 4.2 java 1.6 mono 2.10 (C# 4.0)
version
 
$ g++ —version $ gcc —version $ javac -version $ mcs —version
libraries used
 
STL and Boost Foundation Framework Java API Base Class Library
source, header, object file suffix .cpp .hpp .o .m .h .o .java none .class .cs none .exe or.dll
null
 
NULL NULL null null
printf
 
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 names A_MACRO_NAME
AClassName
AMethodName() or a_method_name()
a_variable_name
A_MACRO_NAME
AClassName
[obj aMsgName:arg aLabelName:arg]
aVariableName
AClassName
aMethodName()
aVariableName
AClassName
AMethodName()
aVariableName
coalesce
 
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 c java c#
declare primitive type on stack int 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 heap int *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 heap delete i; #include <stdlib.h>

free(ip);
garbage collected garbage collected
value of uninitialized primitive types same 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-initialized compiler prevents use of uninitialized variables in some circumstances, and zero-initializes in others
boolean types
 
bool BOOL boolean bool
signed integer types signed char 1+ byte
short int 2+ bytes
int 2+ bytes
long int 4+ bytes
long long int 4+ bytes
signed char 1+ byte
short int 2+ bytes
int 2+ bytes
long int 4+ bytes
long long int 4+ bytes
byte 1 byte
short 2 bytes
int 4 bytes
long 8 bytes
sbyte 1 byte
short 2 bytes
int 4 bytes
long 8 bytes
unsigned integer types unsigned char: 8+
unsigned short int 2 bytes+
unsigned int 2 bytes+
unsigned long int 4+ bytes
unsigned long long int 4+ bytes
unsigned char: 8+
unsigned short int 2 bytes+
unsigned int 2 bytes+
unsigned long int 4+ bytes
unsigned long long int 4+ bytes
char 2 bytes byte 1 byte
ushort 2 bytes
uint 4 bytes
ulong 8 bytes
floating point and decimal types float
double
long double
float
double
long double
float 4 bytes
double 8 bytes
float 4 bytes
double 8 bytes
decimal 12 bytes
typedef typedef int customer_id;
customer_id cid = 3;
typedef int customer_id;
customer_id cid = 3;
none none
enum enum 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 c java c#
true and false
 
true false YES NO true false true false
falsehoods
 
false 0 0.0 NULL 0 0.0 NULL false false
logical operators && || !
and or not
&& || ! && || ! && || !
relational operators == != < > <= >= == != < > <= >= == != < > <= >= == != < > <= >=
arithmetic operators
 
+ - * / % + - * / % + - * / % + - * / %
division by zero process sent a SIGFPE signal process sent a SIGFPE signal throws java.lang.ArithmeticException throws System.DivideByZeroException
power #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 atan2
Math.sqrt Math.exp Math.log none Math.log10 Math.sin Math.cos Math.tan Math.asin Math.acos Math.atan Math.atan2 using System;
 
Math.Sqrt Math.Exp Math.Log none Math.Log10 Math.Sin Math.Cos Math.Tan Math.Asin Math.Acos Math.Atan Math.Atan2
arithmetic 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 c java c#
type
 
std::string NSString java.lang.String string
literal
 
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 string string literals can extend over multiple lines, but the newlines do not appear in the resulting string no string literals can extend over multiple lines, but the newlines do not appear in the resulting string
escapes
 
\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 \ooo
allocate string string *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.Length
comparison string *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 comparison object identity comparison object identity comparison value comparison
to C string
 
s->c_str() [s UTF8String] none none
string 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)
concatenate string *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"
substring string("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('');
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 c java c#
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 c java c#
date/time type
 
java.util.Date System.DateTime
current 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 c java c#
allocate array on stack int a[10]; int a[10]; arrays must be allocated on heap arrays must be allocated on heap
allocate array on heap int *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 heap delete[] a; #include <stdlib.h>
free(a);
garbage collected garbage collected
array literal int 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.length a.Length
array out-of-bounds result undefined, possible SIGSEGV raises NSRangeException exception ArrayIndexOutOfBoundsException IndexOutOfRangeException
array iteration int 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 definition class 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 declaration MedalCount spain; struct medal_count spain; MedalCount spain = new MedalCount(); MedalCount spain = new MedalCount();
struct initialization MedalCount 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 constructor no object literal syntax; define a constructor
struct member assignment 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;
spain.country = "Spain";
spain.gold = 3;
spain.silver = 7;
spain.bronze = 4;
struct member access 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; 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 push vec.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.Count
vector access vec[0]
vec.at(0)
[a objectAtIndex:0] vec.elementAt(0) l[0]
vector out of bounds result vec[] has undefined behavior
vec.at() raises out_of_range
raises NSRangeException throws ArrayIndexOutOfBoundsException throws System.ArgumentOutOfRangeException
vector iteration int 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 c java c#
pair pair<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 access m["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.Count
map remove element m.erase(m.find("hello")); [dict removeObjectForKey:@"hello"]; m.remove("hello"); dict.Remove("hello");
map element not found result NULL NULL null throws KeyNotFoundException
in System.Collections.Generic
map iterate map<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 c java c#
pass by value void 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 value primitive types are always passed by value
pass by address void 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);
none none
pass by reference void use_iref(int& i) {
printf("using iref: %d", i);
}
int i = 7;
use_iref(i);
none objects and arrays are always passed by reference objects and arrays are always passed by reference
default argument value float log(float exp, float base=10.0) { none use method overloading use method overloading
named parameters none +(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];
none added 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 overloading yes method overloading only yes yes
variable number of arguments use C; use default values or function overloading for finite number of arities use C; use method overloading for finite arities public 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 overloading Rational Rational::operator+(Rational& o) {
  return Rational(this->num*o.denom + o.num*this->denom, this->denom * o.denom);
}
none none public 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 c java c#
for int 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;
}
if 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;
}
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++;
}
switch 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;
}
switch(i) {
case 0:
  0;
  break;
case 1:
  1;
  break;
default:
  -1;
  break;
}
throw exception throw exception(); NSException *exc = [NSException exceptionWithName:@"error" reason:@"failed" userInfo:nil];
@throw exc;
throw new Exception("failed"); throw new System.Exception("failed");
catch exception try {
  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 clause use 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 exceptions no no yes no
files
c++ objective c java c#
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++) {
  f << 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 c java c#
processes and environment
c++ objective c java c#
signature of main int 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 executable pathname of executable first command line argument first command line argument
environment 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 c java c#
declare namespace namespace 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 file yes no yes
namespaces map to directories no yes no
import namespace using 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 namespace using namespace foo;
cout << bar::Baz::ANSWER << endl;
none none
import symbol using foo::bar::Baz;
cout << Baz::ANSWER << endl;
import foo.bar.Baz;
System.out.println(Baz.ANSWER);
none
import static symbol none import static foo.bar.Baz.ANSWER;
System.out.println(ANSWER);
none
import position
 
anywhere a statement is legal after package and before type definitions outside of class definitions
using a symbol that hasn't been imported cout << foo::bar::Baz::ANSWER << endl; System.out.println(foo.bar.Baz.ANSWER); using System.Console;
WriteLine(foo.bar.Baz.ANSWER);
objects
c++ objective c java c#
define class Rational.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;
}
@end
public 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 location top level, class block, or function block top level top level, class block, or function block for anonymous classes
constructor Rational::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 object Rational 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);
destructor Rational::~Rational() {}; -(void) dealloc {
  [super dealloc];
  printf("deallocated…");
}
protected void finalize() throws Throwable {
  super.finalize();
}
~Rational() {
  perform cleanup
}
destroy object
 
delete r2; [r release]; none none
define method int 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 method r1.height();
r2->height();
[r1 height]; r.height(); r.Height();
dynamic dispatch declare as virtual in base class dispatch always dynamic dispatch dynamic by default declare as virtual in base class and override in derived class
static dispatch dispatch static by default dispatch always dynamic declare 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 class
define class method declare static in class definition precede 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 definition declare static in class definition
invoke class method
name of receiver this self this this
access control access 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;
}
@end
access 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 class possible but not useful none (new Object() { public void hello() { System.out.println("hello!"); } }).hello();
subclass class 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 constructor Integer::Integer(int n) : Rational(n, 1) {
}
super(n, 1);
mark class underivable or method unoverrideable none none final sealed
root class
 
none NSObject java.lang.Object System.Object
root class methods none autorelease
class
conformsToProtocol:
hash
isEqual:
isKindOfClass:
isProxy
performSelector:
performSelector:withObject:
performSelector:withObject:withObject:
release
respondsToSelector:
retain
retainCount
self
superclass
clone()
equals()
finalize()
getClass()
hashCode()
toString()
Equals()
Finalize()
GetHashCode()
GetType()
MemberwiseClone()
ReferenceEquals()
ToString()
generic types
c++ objective c java c#
define generic type template <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 type Foo<string> f = Foo<string>("foo"); Foo<String> f = new Foo<String>("foo"); Foo<string> f = new Foo<string>("foo");
generic function template <class C>
C add(C a, C b) {
  return a + b;
}
generic array template <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 parameter template <int N>
int add(int i) {
  return N+i;
}
 
cout << add<7>(3) << endl;
template parameter
template specialization
multiple type parameters template <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 parameters Pair<int, Foo<string> > p =
  Pair<int, Foo<string> >(
    7, Foo<string>("foo"));
template parameters
reflection
c++ objective c java c#
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 identifier typeid(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 c java c#
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:

 .cc .cp .cxx .cpp .CPP .c++ .C

null

C

A typical definition:

#define NULL (void *)0

C++

A typical definition:

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 of NSAutoreleasePool. 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:

Integer i = new Integer(0);

The compiler may instantiate the wrapper class implicitly; this is called boxing. The compiler also permits use of a wrapper class in the place of the primitive type, or unboxing.

C#

C# behavior is like Java. Note that C# lacks specific wrapper classes for each primitive data type.

free primitive type on heap

How to free the memory for a primitive type that was allocated on the heap.

value of uninitialized types

The value assigned to primitive types that are not explicitly initialized.

C++

The default constructors for primitive types will be called in some circumstances.

C#

Section 5.3.1 of ECMA-334 describes when variables are zero-initialized.

boolean types

C

The following definitions are common:

typedef int BOOL;
#define TRUE 1
#define FALSE 0

Objective C

From objc.h:

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 int int32_t;

The rest of the code would declare integers that need to be 32 bits in size using int32_t and if the code needed to be ported to a platform with a 16 bit int, only a single place in the code requires change. In practice the typedef abstraction is leaky because functions in the standard library such as atoi, strtol, or the format strings used by printf depend on the underlying type used.

Java

Java has well defined integer sizes so typedef is not needed as a portability aid. In other situations where a C programmer would use a typedef for data abstraction, a Java programmer must either define a class or retain the raw primitive type throughout the code.

enum

C

Enums were added to the C standard when the language was standardized by ANSI in 1989.

An enum defines a family of integer constants. If an integer value is not explicitly provided for a constant, it is given a value one greater than the previous constant in the list. If the first constant in the list is not given an explicit value, it is assigned a value of zero. it is possible for constants in a list to share values. For example, in the following enum, a and c are both zero and b and d are both one.

enum { a=0, b, c=0, d };

A typedef can be used to make the enum keyword unnecessary in variable declarations:

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:

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

typedef enum { mon, tue, wed, thu, fri, sat, sun } day_of_week2;
day_of_week2 d2 = 10;

C++

C++ enums are more strongly typed the C enums. The compiler rejects attempts to assign a value to an enum variable that is not in the enumerated list. The following code:

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

produces an error like the following:

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:

typedef int BOOL;
#define TRUE 1
#define FALSE 0

Objective C

From objc.h:

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

falsehoods

Values which evaluate as false in the conditional expression of an if statement.

logical operators

The logical operators.

In all languages on this sheet the && and || operators short circuit: i.e. && will not evaluate the 2nd argument if the 1st argument is false, and || will not evaluate the 2nd argument if the 1st argument is true. If the 2nd argument is not evaluated, side-effects that it contains are not executed.

C++

C++ defines and, or, and not to be synonyms of &&, ||, and !, with the same semantics and precedence.

Java

The arguments of the logical operators must be of type boolean.

C#

The arguments of the logical operators must be of type bool.

relational operators

Binary operators which return boolean values.

arithmetic operators

The arithmetic binary operators: addition, subtraction, multiplication, division, modulus.

division by zero

The results of division by zero.

C, C++, Objective C

The behavior for division by zero is system dependent; the behavior described is nearly universal on Unix.

C#

It is a compilation error to divide by a zero constant. Division by a variable set to zero results in a runtime exception.

power

How to perform exponentiation.

C++

powm1 is an abbreviation for "power minus one". Hence the need to add one to get the answer.

absolute value

The absolute value of a numeric quantity.

transcendental functions

The square root function and the transcendental functions.

arithmetic truncation

Functions for converting a float to a nearby integer value.

C:

The math.h library also provides floor and ceil which return double values.

Java:

Math.floor and Math.ceil return double values.

random integer

How to generate a random integer.

bit operators

The bit operators: left shift, right shift, and, or, xor, and complement.

C++

bitand, bitor, and compl are synonyms of &, |, and ~ with identical precedence and semantics.

String Footnotes

type

The type for strings.

literal

The syntax for string literals.

newline in literal?

Can a newline be used in a string literal? Does the newline appear in the resulting string object?

escapes

Escape sequences that can be used in string literals.

allocate string

How to allocate a string.

Java

The following code

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:

String t = s;

string length

string comparison

C

Returns 1, 0, or -1 depending upon whether the first string is lexicographically greater, equal, or less than the second. The variants strncmp, strcasecmp, and strncasecmp can perform comparisons on the first n characters of the strings or case insensitive comparisons.

**C++

string::compare returns a positive value, 0, or a negative value depending upon whether the receiver is lexicographically greater, equal, or less than the argument. C++ overload the comparison operators (<, >, ==, !=, <=, >=) so that they can be used for string comparison.

Objective C
compare will return -1, 0, or 1.

Java

compareTo will return a negative value, 0, or a positive value.

C#

CompareTo will return -1, 0, or 1.

to C string

string to number

C

strtoimax, strtol, strtoll, strtoumax, strtoul, and strtoull take three arguments:

intmax_t
strtoimax(const char *str, char **endp, int base);

The 2nd argument, if not NULL, will be set to first character in the string that is not part of the number. The 3rd argument can specify a base between 2 and 36.

strtof, strtod, and strtold take three arguments:

double
strtod(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:

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:

using System;
using System.Globalization;

CultureInfo enUS = new CultureInfo("en-US");
DateTime startEpoch = DateTime.ParseExact("1970-01-01 00:00:00 -00", "yyyy-MM-dd HH:mm:ss zz", enUS);

Console.WriteLine(startEpoch.ToFileTimeUtc() / (100*1000*1000));

strftime

How to use a format string to display a date/time object.

The canonical example of doing this is the strftime function from the C standard library which defines used letters prefix by percent signs as conversion specification characters, e.g. %Y-%m-%d.

strptime

How to use a format string to parse date data from a string.

Array Footnotes

allocate array on stack

How to allocate an array on the stack.

allocate array on heap

How to allocate an array on the heap.

free array on heap

How to free an array that was allocated on the heap.

array literal

Objective C

NSArray can only store instances of NSObject. For primitive types, use C arrays.

Java

Java permits arrays to be declared with C-style syntax:

int a[] = {1,2,3}

array element access

C

Arrays can be manipulated with pointer syntax. The following sets x and y to the same value:

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:

char *a[] = { "Bob", "Ned", "Amy", NULL };
int i;
for (i=0; a[i]; i++) {
  printf("%s\n", a[i]);
}

struct definition

A struct provides names for elements in a predefined set of data and permits the data to be accessed directly without the intermediation of getters and setters. C++, Java, and C# classes can be used to define structs by making the data members public. However, public data members violates the uniform access principle.

C++:

From The C++ Programming Language: 3rd Edition:

by definition, a struct is a class in which members are by default public; that is,

    struct s { ...

is simply shorthand for

    class s { public: ...

struct declaration

struct initialization

C

The literal format for a struct can only be used during initialization. If the member names are not provided, the values must occur in the order used in the definition.

struct member assignment

struct member access

C

The period operator used for member access has higher precedence than the pointer operator. Thus parens must be used
to get at the member of a struct referenced by a pointer:

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:

printf("The winner (%s) earned %d silver medals", winner->country, winner->silver);

vector declaration

vector push

vector pop

vector size

vector access

vector out of bounds

vector iteration

Dictionary Footnotes

pair

map declaration

C:

For those interested in an industrial strength hashtable implementation for C, here is the header file and the source file for the hashtable used by Ruby.
For those interested in a "Computer Science 101" implementation of a hashtable, here is a simpler source file and header file.

map access

map size

map remove

map element not found result

map iterator

Function Footnotes

pass by value

pass by address

pass by reference

default argument value

named parameters

objective C:

Named parameters must be invoked in the order in which they are defined in the method signature.

C#:

Named parameter do not need to be invoked in the order in which they are defined in the method signature. Additionally, their use in
invocation is optional: the arguments can be provided without names in which case the definition order must be used.

function overloading

variable number of arguments

C

The stdarg.h library supports variable length functions, but provides no means for the callee to determine how many arguments were provided. Two techniques for communicating the number of arguments to the caller are (1) devote one of the non-variable arguments for the purpose as illustrated in the table above, or (2) set the last argument to a sentinel value as illustrated below. Both techniques permit the caller to make a mistake that can cause the program to segfault. printf uses
the first technique, because it infers the number of arguments from the number of format specifiers in the format string.

char* concat(char* first,  ...) {
  int len;
  va_list ap;
  char *retval, *arg;
  va_start(ap, first);
  len = strlen(first);
  while (1) {
    arg = va_arg(ap, char*);
    if (!arg) {
      break;
    }
    len += strlen(arg);
  }
  va_end(ap);
  retval = calloc(len+1,sizeof(char));
  va_start(ap, first);
  strcpy(retval, first);
  len = strlen(first);
  while (1) {
    arg = va_arg(ap, char*);
    if (!arg) {
      break;
    }
    printf("copying %s\n", arg);
    strcpy(retval+len, arg);
    len += strlen(arg);
  }
  va_end(ap);
  return retval;
}

An example of use:

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:

int a = 1;
int b = -1;
int c = 0;
if (a > 0)
if (b > 0)
  c=1;
else
  c= 2;

while

If the body of a while loop consists of a single statement the curly braces are optional:

int i = 0;
while (i<10)
  printf("%d\n", ++i);

switch

A switch statement branches based on the value of an integer or an integer expression. Each clause must be terminated by a break statement or execution will continue into the following clause.

throw exception

C++

C++ code can throw or catch any type of object or primitive data type. The C++ standard library throws subclasses of std::exception, which does not have a message member.

Objective C

Objective C can only throw an instance of NSException or one of its subclasses.

Java

Java can only throw an implementation of java.lang.Throwable.

C#

C# can only throw an instance of System.Exception of one of its subclasses.

catch exception

C++

Exceptions can be caught by value or by reference. If the exception is an object and it is caught by value, the copy constructor and the desctructor will be invoked.

Objective C

Exceptions are thrown and caught by pointer value.

finally clause

C++

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.

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:

! * ' ( ) ; : @ & = + $ , / ? # [ ]

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

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 and real, 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 or static. 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-circuit 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. Microsoft 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 Terminology C#/.NET Terminology
Java C#
Java bytecode Common Intermediate Language (CIL)
JVM Virtual Execution System (VES)
Java API .NET Framework
Java VM Specification Common 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.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License