# top//a side-by-side reference sheet//
[#grammar-invocation grammar and invocation] | [#variables-expressions variables and expressions] | [#arithmetic-logic arithmetic and logic] | [#strings strings] | [#regexes regexes] | [#dates-time dates and time] | [#fixed-length-arrays fixed-length-arrays] | [#resizable-arrays resizable arrays] | [#dictionaries dictionaries] | [#functions functions] | [#execution-control execution control] | [#concurrency concurrency] | [#file-handles file handles] | [#files files] | [#file-fmt file formats] | [#directories directories] | [#processes-environment processes and environment] | [#option-parsing option parsing] | [#libraries-namespaces libraries and namespaces] | [#objects objects] | [#user-defined-types user-defined types] | [#cpp-macros c preprocessor macros] | [#net-web net and web] | [#unit-tests unit tests] | [#debugging-profiling debugging and profiling]
||||||||~ # version[#version-note version]||
||~ ||~ [#c c]||~ [#go go]||~ [#java java]||
||# version-used[#version-used-note version used] _
@< >@||##gray|//C11//, //gcc 4.8//, //clang 3.5//##||##gray|//1.10//##||##gray|//java 1.7//##||
||# show-version[#show-version-note show version] _
@< >@||$ gcc @@–@@version||$ go version||$ javac -version||
||# implicit-prologue[#implicit-prologue-note implicit prologue]||#include _
#include _
#include _
#include _
#include _
#include ||import “fmt”||##gray|//none//##||
||||||||~ # grammar-invocation[#grammar-invocation-note grammar and invocation]||
||~ ||~ c||~ go||~ java||
||# hello-world[#hello-world-note hello world]||$ cat hello.c _
#include _
_
int main(int argc, char @@@@argv) { _
@< >@printf(“Hello, World!\n”); _
} _
_
$ gcc hello.c _
_
$ ./a.out _
Hello, World!||$ cat hello.go _
package main _
import “fmt” _
_
func main() { _
@< >@fmt.Printf(“Hello, World!\n”) _
} _
_
$ go build hello.go _
_
$ ./hello _
Hello, World!||$ cat Hello.java _
public class Hello { _
@< >@public static void main(String[] args) { _
@< >@@< >@System.out.println(“Hello, World!”); _
@< >@} _
} _
_
$ javac Hello.java _
_
$ java Hello||
||# file-suffixes[#file-suffixes-note file suffixes] _
##gray|//source, header, object file//##||.c .h .o||.go ##gray|//none//## ##gray|//none//##||Foo.java _
##gray|//none//## _
Foo.class _
_
##gray|Foo.java //must define a single top level class// Foo##||
||# stmt-terminator[#stmt-terminator-note statement terminator]||;||; ##gray|//or sometimes newline//## _
_
##gray|//a new line terminates a statement when the last token on the line is _
@< >@(1) an identifier, _
@< >@(2) a numeric, character, or string literal, _
@< >@(3) one of the keywords// break, continue, _
@< >@@< >@@< >@fallthrough, //or// return, // _
@< >@(4) one of// ++, @@–@@, ), ], //or// }##||;||
||# top-level-stmt[#top-level-stmt-note top level statements]|| || ||##gray|//each file contains the following elements in order: _
_
(1) optional package directive _
(2) zero or more import directives _
(3) one public class definition and zero or more private class definitions//##||
||# block-delimiters[#block-delimiters-note block delimiters] _
@< >@||{ ##gray|//…//## }||{ ##gray|//…//## }||{ }||
||# eol-comment[#eol-comment-note end-of-line comment] _
@< >@||@@//@@ ##gray|//comment//##||@@//@@ ##gray|//comment//##||##gray|@@//@@ comment##||
||# multiple-line-comment[#multiple-line-comment-note multiple line comment]||/* ##gray|//comment line//## _
##gray|//another line//## /||/ ##gray|//comment line//## _
##gray|//another line//## /||##gray|/ comment _
another comment /##||
||||||||~ # variables-expressions[#variables-expressions-note variables and expressions]||
||~ ||~ c||~ go||~ java||
||# local-var[#local-var-note variable]||##gray|/ if inside function, memory allocated on stack: /## _
int i; _
int j = 3; _
_
##gray|/ memory allocated on heap: */## _
int *ptr = malloc(sizeof ptr); _
##gray|/ if malloc fails, it returns NULL and sets errno to ENOMEM */## _
*ptr = 7;||##gray|@@//@@ memory allocated on stack:## _
var i int _
_
##gray|@@//@@ allocated on stack; type inferred from literal:## _
j := 3 _
_
##gray|@@//@@ memory allocated on heap:## _
ptr := new(int) _
ptr = 7||int i; _
int j = 3;||
||# free-heap[#free-heap-note free heap] _
@< >@||free(ptr);||##gray|//none; uses garbage collection//##||##gray|//garbage collected//##||
||# global-var[#global-var-note global variable]||##gray|/ in foo.c, outside of any function: /## _
int x = 7; _
_
##gray|/ to declare in bar.c: /## _
extern int x;||##gray|@@//@@ foo.go:## _
package foo _
_
##gray|@@//@@ capitalized top-level identifiers are exported:## _
var X = 7 _
_
##gray|@@//@@ bar.go:## _
package bar _
import foo _
_
##gray|@@//@@ package scope:## _
var y = 3 _
_
func baz() { _
@< >@##gray|@@//@@ local scope:## _
@< >@var z = 5 _
_
@< >@fmt.Println(foo.X + y + z) _
}||##gray|//foo/Foo.java://## _
package foo; _
_
##gray|@@//@@ globals must be declared inside a _
@@//@@ class:## _
public class Foo { _
@< >@public static int bar; _
} _
_
##gray|//UseFoo.java://## _
import foo.Foo; _
_
public class UseFoo { _
@< >@public static void main(String[] args) { _
@< >@@< >@System.out.println(Foo.bar); _
@< >@} _
}||
||# uninitialized-var[#uninitialized-var-note uninitialized variable]||##gray|//The behavior of reading from uninitialized stack variables or unitialized memory allocated by// malloc //is undefined. _
_
Global and static variables are zero-initialized. _
_
Heap variables allocated by// calloc //have their bytes zeroed.//##||##gray|//Every type has a zero value. For numeric types it is zero and for strings it is the empty string.//##||##gray|//Compilation error if local variables are not explicitly initialized. _
_
Global variables and object attributes will be zero-initialized if not explicitly initialized. Zero values are zero for numeric types, false for booleans, and null for reference types.//##||
||# compile-time-const[#compile-time-const-note compile time constant]||##gray|/ usually preprocessor is used: */## _
#define PI 3.14||const Pi = 3.14||final double pi = 3.14;||
||# immutable-var[#immutable-var-note immutable variable] _
@< >@||const int i = rand();||##gray|//none//##||import java.util.Random; _
_
Random rnd = new Random(); _
final int i = rnd.nextInt(100);||
||# assignment[#assignment-note assignment]||i = 3;||##gray|@@//@@ defines variable of appropriate type:## _
i := 3 _
_
##gray|@@//@@ variable must already be declared:## _
i = 3||int n; _
n = 3;||
||# parallel-assignment[#parallel-assignment-note parallel assignment]||##gray|//none//##||##gray|@@//@@ define variables of appropriate type:## _
m, n := 3, 7 _
_
##gray|@@//@@ x and y must already be declared:## _
x, y = 2, 8||##gray|//none//##||
||# swap[#swap-note swap]||int x = 1, y = 2, tmp; _
_
tmp = x; _
x = y; _
y = tmp;||x, y = y, x||int x = 1, y = 2, tmp = 0; _
_
tmp = x; _
x = y; _
y = tmp;||
||# compound-assignment[#compound-assignment-note compound assignment]||##gray|//arithmetic://## _
+= -= *= /= %= _
_
##gray|//bit://## _
@@<<= >>= &= |= ^=@@||##gray|//arithmetic://## _
+= -= *= /= %= _
_
##gray|//bit://## _
@@<<= >>= &= |= ^=@@||+= -= = /= %= _
@@<<= >>= @@&= ^= |= _
_
##gray|@@>>=@@ //is arithmetic right shift,// @@>>>=@@ //is logical right shift//##||
||# incr-decr[#incr-decr-note increment and decrement]||##gray|//premodifiers://## _
++i @@–@@i _
_
##gray|//postmodifiers://## _
i++ i@@–@@||##gray|//postmodifiers only; cannot be used in expressions://## _
i++ i@@–@@||int n = 1; _
int one = n++; _
int three = ++n; _
int two = @@–@@n;||
||# addr[#addr-note address]||int i = 3; _
int ptr = &i;||i := 3 _
_
var ptr *int _
ptr = &i _
ptr2 := &i||##gray|//none//##||
||# dereference[#dereference-note dereference] _
@< >@||int i2 = *ptr;||i2 := ptr||##gray|//none//##||
||# type-size[#type-size-note type size]||##gray|/ put type inside parens: /## _
sizeof (int) _
_
##gray|/ expressions and values don’t require parens: */## _
sizeof 1 + 1||import “unsafe” _
_
##gray|@@//@@ use expression or name of variable with type:## _
unsafe.Sizeof(i) _
unsafe.Sizeof(1 + 1)||##gray|//none//##||
||# addr-arith[#addr-arith-note address arithmetic]||int a[] = {3, 2, 1, 0}; _
_
for (int *p = a; *p; ++p) { _
@< >@printf(“%d\n”, p); _
}||##gray|//none//##||##gray|//none//##||
||# null[#null-note null] _
@< >@||##gray|/ pointer types only: /## _
NULL||##gray|@@//@@ cannot be stored in numeric or string variable:## _
nil||null||
||# null-test[#null-test-note null test] _
@< >@||ptr == NULL||ptr == nil||ref == null||
||# conditional-expr[#conditional-expr-note conditional expression] _
@< >@||x > 0 ? x : -x||##gray|//none//##||x > 0 ? x : -x||
||||||||~ # arithmetic-logic[#arithmetic-logic-note arithmetic and logic]||
||~ ||~ c||~ go||~ java||
||# boolean-type[#boolean-type-note boolean type] _
@< >@||int _
_
##gray|/ includes type for consistency with C++: /## _
#include _
_
bool||bool||boolean||
||# true-false[#true-false-note true and false] _
@< >@||1 0 _
_
##gray|/ includes identifiers for consistency with C++: */## _
#include _
_
true false||true false||true false||
||# falsehoods[#falsehoods-note falsehoods] _
@< >@||0 0.0 NULL false||false||false||
||# logical-op[#logical-op-note logical operators] _
@< >@||&& @@||@@ !||&& @@||@@ !||&& @@||@@ !||
||# relational-op[#relational-op-note relational operators] _
@< >@||== != < > <= >=||== != < > <= >=||== != < > <= >=||
||# int-type[#int-type-note integer type]||signed char ##gray|//1+ bytes//## _
short int ##gray|//2+ bytes//## _
int ##gray|//2+ bytes//## _
long int ##gray|//4+ bytes//## _
long long int ##gray|//4+ bytes//## _
_
##gray|//types with portable sizes are defined in// stdint.h:## _
int8t int16t int32t int64t||int _
int8 _
int16 _
int32 _
int64||byte n1;@< >@##gray|@@//@@ 1 byte## _
short n2; ##gray|@@//@@ 2 bytes## _
int n3;@< >@##gray|@@//@@ 4 bytes## _
long n4;@< >@##gray|@@//@@ 8 bytes##||
||# unsigned-type[#unsigned-type-note unsigned type]||unsigned char: ##gray|//1+ bytes//## _
unsigned short int ##gray|//2 bytes+//## _
unsigned int ##gray|//2 bytes+//## _
unsigned long int ##gray|//4+ bytes//## _
unsigned long long int ##gray|//4+ bytes//## _
_
##gray|//types with portable sizes are defined in// stdint.h:## _
uint8t uint16t uint32t uint64t||uint8 (byte) _
uint16 _
uint32 _
uint64||char n1;@< >@##gray|@@//@@2 bytes##||
||# float-type[#float-type-note float type]||float ##gray|//4 bytes//## _
double ##gray|//8 bytes//## _
long double ##gray|//16 bytes//## _
_
##gray|//registers may be larger on some systems//##||float32 _
float64||float x1;@< >@##gray|@@//@@ 4 bytes## _
double x2; ##gray|@@//@@ 8 bytes##||
||# arith-op[#arith-op-note arithmetic operators] _
@< >@||@@+@@ - * / %||@@+@@ - * / %||@@+@@ - * / %||
||# int-div[#int-div-note integer division] _
@< >@||3 / 7||3 / 7||##gray|@@//@@ evaluates to 2:## _
7 / 3||
||# int-div-zero[#int-div-zero-note integer division by zero] _
@< >@||##gray|//system dependent; process often sent a// SIGFPE //signal//##||##gray|//on Unix, process sent a// SIGFPE //signal//##||##gray|//throws//## java.lang.ArithmeticException||
||# float-div[#float-div-note float division] _
@< >@||3 / (float)7||3 / float32(7)||7 / (float)3||
||# float-div-zero[#float-div-zero-note float division by zero]||##gray|/* these are float values but not literals: /## _
inf, nan, or -inf||##gray|@@//@@ these are float values but not literals:## _
+Inf, NaN, ##gray|//or//## -Inf _
_
##gray|@@//@@ to get the float values:## _
import “math” _
_
math.Inf(1) math.Nan() math.Inf(-1)||Float.POSITIVE_INFINITY _
Float.NaN _
Float.NEGATIVE_INFINITY _
_
##gray|//constants with same names defined in//## Double||
||# power[#power-note power]||#include _
_
pow(2.0, 3.0)||import “math” _
_
math.Pow(2.0, 3.0)||Math.pow(2.0, 32.0);||
||# sqrt[#sqrt-note sqrt]||#include _
_
sqrt(2);||include “math” _
_
math.Sqrt(2)||Math.sqrt(2)||
||# sqrt-negative-one[#sqrt-negative-one-note sqrt -1]||#include _
_
##gray|/ nan /## _
double x = sqrt(-1.0);||import “math” _
_
##gray|@@//@@ NaN## _
x := math.Sqrt(-2.0) _
_
import “math/cmplx” _
_
##gray|@@//@@ (0+1.41421356i)## _
z := cmplx.Sqrt(-2.0)||Double.NaN||
||# transcendental-func[#transcendental-func-note transcendental functions]||#include _
_
exp log log2 log10 _
sin cos tan _
asin acos atan _
atan2||include “math” _
_
math.Exp math.Log math.Log2 math.Log10 _
math.Sin math.Cos math.Tan _
math.Asin math.Acos math.Atan _
math.Atan2||Math.exp Math.log ##gray|//none//## Math.log10 _
Math.sin Math.cos Math.tan _
Math.asin Math.acos Math.atan _
Math.atan2||
||# transcendental-const[#transcendental-const-note transcendental constants]||#include _
_
M_PI _
M_E||import “math” _
_
math.Pi _
Math.E||Math.E _
Math.PI||
||# float-truncation[#float-truncation-note float truncation]||#include _
@< >@ _
double d = 3.77; _
@< >@ _
long trunc = (long)d; _
long rnd = round(d); _
long flr = floorl(d); _
long cl = ceill(d);||include “math” _
_
x = 3.77 _
_
trunc := int(x) _
##gray|//none//## _
flr := int(math.Floor(x)) _
cl := int(math.Ceil(x))||(long)3.77 _
Math.round(3.77) _
(long)Math.floor(3.77) _
(long)Math.ceil(3.77)||
||# absolute-val[#absolute-val-note absolute value]||#include @< >@##gray|/ fabs() */## _
_
int i = abs(-7); _
float x = fabs(-7.77);||include “math” _
_
##gray|//none//## _
math.Abs(-7.77)||Math.abs(-7) _
Math.abs(-7.77)||
||# int-overflow[#int-overflow-note integer overflow]|| || ||##gray|//modular arithmetic//##||
||# float-overflow[#float-overflow-note float overflow]|| || ||Float.POSITIVE_INFINITY||
||# float-limits[#float-limits-note float limits] _
##gray|//largest finite float, smallest positive float//##|| || ||Float.MAX_VALUE _
Float.MIN_VALUE _
Double.MAX_VALUE _
Double.MIN_VALUE||
||# complex-type[#complex-type-note complex type]||float complex ##gray|//8 bytes//## _
double complex ##gray|//16 bytes//## _
long double complex ##gray|//32 bytes//##||complex64 _
complex128||##gray|//none//##||
||# complex-construction[#complex-construction-note complex construction]||#include _
_
double complex z; _
z = 1.0 + 2.0 * I; _
_
##gray|/* C11: /## _
double complex z = CMPLX(1.0, 2.0);||var z complex128 = 1.0 + 2.0i||##gray|//none//##||
||# complex-decomposition[#complex-decomposition-note complex decomposition] _
##gray|//real and imaginary component, argument, absolute value, conjugate//##||#include _
_
double x; _
double complex w; _
_
x = creal(z); _
x = cimag(z); _
x = carg(z); _
x = cabs(z); _
w = conj(z);||import “math/cmplx” _
_
var x float64 _
var w complex128 _
_
x = real(z) _
x = imag(z) _
x = cmplx.Phase(z) _
x = cmplx.Abs(z) _
w = cmplx.Conj(z)||##gray|//none//##||
||# random-num[#random-num-note random number] _
##gray|//uniform integer, uniform float//##||##gray|/ lrand48 returns value in [0, 231 - 1]: /## _
long n = lrand48(() % 100; _
_
##gray|/ Value in interval [0.0, 1.0): */## _
double x = drand48();||import “math/rand” _
_
n := rand.Intn(100) _
x := rand.Float64()||import java.util.Random; _
_
Random rnd = new Random(); _
_
int i = rnd.nextInt(100); _
double x = rnd.nextDouble(); _
double y = rnd.nextGaussian();||
||# random-seed[#random-seed-note random seed]||srand48(17);||import “math/rand” _
_
rand.Seed(17)||import java.util.Random; _
_
Random rnd = new Random(); _
_
rnd.setSeed(17); _
_
##gray|@@//@@ seed can also be passed to constructor##||
||# bit-op[#bit-op-note bit operators] _
@< >@||@@ << >> & | ^ ~ @@||@@<< >> & |@@ ##gray|//none//## ^||@@ << >> & | ^ ~ @@ _
_
##gray|@@>>@@ //is arithmetic right shift, @@>>>@@ is logical right shift//##||
||# binary-octal-hex[#binary-octal-hex-note binary, octal, and hex literals]||##gray|//none//## _
052 _
0x2a||##gray|//none//## _
052 _
0x2a||0b101010 _
052 _
0x2a||
||# radix[#radix-note radix] _
##gray|//convert integer to and from string with radix//##|| || ||Integer.toString(42, 7) _
Integer.parseInt(“60”, 7)||
||||||||~ # strings[#strings-note strings]||
||~ ||~ c||~ go||~ java||
||# str-type[#str-type-note string type] _
@< >@||char * _
wchar_t * _
_
##gray|wchar_t //is typically 32 bits on Linux and 16 bits on Windows.//##||##gray|@@//@@ immutable:## _
string _
_
##gray|@@//@@ mutable:## _
[]byte||##gray|@@//@@ immutable:## _
java.lang.String _
_
##gray|@@//@@ mutable:## _
java.lang.StringBuffer _
_
##gray|@@//@@ StringBuffer //has// append(), delete(), _
@@//@@ deleteCharAt(), insert(), replace(), setCharAt().##||
||# str-literal[#str-literal-note string literal] _
@< >@||##gray|/* string in initialized data segment: */## _
char *s = “hello”; _
wchar_t ws = L"hello”; _
_
##gray|/ string in heap: */## _
char *s2 = strdup(s); _
wchar_t ws2 = wcsdup(ws); _
_
##gray|/ if strdup cannot allocate memory, it returns NULL and sets _
@< >@errno to ENOMEM. /##||"hello” _
_
##gray|@@//@@ raw string literal:## _
@@hello@@ _
_
##gray|@@//@@ convert literal to mutable string:## _
[]byte(“hello”)||"don’t say"no"”||
||# newline-in-str-literal[#newline-in-str-literal-note newline in string literal]||##gray|/ compiler concatenates literals _
@< >@separated by whitespace: */## _
char s = “first line\n” _
@< >@"second line”;||##gray|@@//@@ backquote literals only:## _
let s := @@first line@@ _
second line@@@@||##gray|//none//##||
||# str-literal-esc[#str-literal-esc-note string escapes]||\a \b \f \n \r \t \v " \’ \? \ _
##gray|//o//## ##gray|//oo//## ##gray|//ooo//## \x##gray|//hh//## \u##gray|//hhhh//## \U##gray|//hhhhhhhh//##||##gray|//Double quote literals only://## _
_
\a \b \f \n \r \t \v \ " _
##gray|//ooo//## \x##gray|//hh//## \u##gray|//hhhh//## \U##gray|//hhhhhhhh//##||\b \f \n \r \t _
\ " \’ _
\u##gray|//hhhh//## ##gray|//o//## ##gray|//oo//## ##gray|//ooo//##||
||# compare-str[#compare-str-note compare strings]||##gray|/ == and < compare memory addresses: /## _
_
strcmp(“hello”, “world”) == 0 _
strcmp(“hello”, “world”) < 0 _
_
wcscmp(L"hello”, L"world”) == 0 _
wcscmp(L"hello”, L"world”) < 0||"hello” == “world” _
“hello” < “world”||"hello”.compareTo(“world”)||
||# str-to-num[#str-to-num-note string to number]||##gray|/ conversion functions: _
@< >@@< >@strtol strtoll _
@< >@@< >@strtoul strtoull _
@< >@@< >@strtof strtod strtold */## _
#include _
_
char *s = “101 dalmations”; _
char rest; _
long n = strtol(s, &rest, 10); _
_
if (n == 0 && errno == EINVAL) _
@< >@printf(“invalid input\n”); _
else if ((n == LONGMAX @@||@@ n == LONGMIN) && errno == ERANGE) _
@< >@printf(“overflow\n”); _
else _
@< >@printf(“%ld %s\n”, n, rest); _
_
##gray|/ wide string conversion functions: _
@< >@@< >@wcstol wcstoll _
@< >@@< >@wcstoul wcstoull _
@< >@@< >@wcstof wcstod wcstold /##||import “strconv” _
_
##gray|@@//@@2nd arg is base, 3rd arg is size of int in bits:## _
i, _ := strconv.ParseInt(“17”, 10, 32) _
_
##gray|@@//@@ 2nd arg is size of float in bits:## _
x, _ := strconv.ParseFloat(“3.14”, 32)||Byte.parseByte(“14”) _
Short.parseShort(“14”) _
Integer.parseInt(“14”) _
Long.parseLong(“14”) _
Float.parseFloat(“14.7”) _
Double.parseDouble(“14.7”)||
||# num-to-str[#num-to-str-note number to string]||long n = 1234; _
_
char buf[100]; _
snprintf(buf, 100, “%ld”, n); _
_
wchar_t buf2[100]; _
swprintf(buf2, 100, L”%ld”, n); _
_
##gray|/ some format specifiers: _
@< >@@< >@%d %ld %lld _
@< >@@< >@%u %lu %llu _
@< >@@< >@%.3f %.3e /##||import “strconv” _
_
##gray|@@//@@ 3rd arg is precision after decimal point; _
@@//@@ 4th arg is size of float in bits:## _
strconv.FormatFloat(3.14, ‘f’, 4, 32) _
_
##gray|@@//@@ 2nd arg is base:## _
strconv.FormatInt(7, 10)||Integer.toString(14) _
Long.toString(14) _
Double.toString(14.7)||
||# split[#split-note split]||##gray|/ strtok_r modifies 1st arg */## _
char *s = strdup(“foo,bar baz”); _
char *sep = “ ,”; _
char *tok, last; _
_
##gray|/ tok is never an empty string: /## _
for (tok = strtok_r(s, sep, &last); _
@< >@@< >@@< >@tok; _
@< >@@< >@@< >@tok = strtok_r(NULL, sep, &last)) _
@< >@printf(“token: %s\n”, tok); _
_
##gray|/ also wcstok */##||import “strings” _
_
s := “foo bar baz” _
parts := strings.Split(s, “ “)||"Bob Ned Amy”.split(“ “)||
||# str-join[#str-join-note join] _
@< >@||##gray|//none//##||import “strings” _
_
parts := []string{"foo”, “bar”, “baz”} _
s := strings.Join(parts, “ “)||String[] a = {"foo”, “bar”, “baz”}; _
String s = String.join(“ “, a);||
||# str-concat[#str-concat-note concatenate]||char *s1 = “hello”; _
char *s2 = “ world”; _
size_t len = strlen(s1) + strlen(s2) + 1; _
char *s3 = (char *)calloc(len, sizeof s3); _
_
strcpy(s3, s1); _
strcat(s3, s2); _
_
##gray|/ also wcscpy and wcscat */##||"hello” + “ world”||"hello” + “ world”||
||# str-replicate[#str-replicate-note replicate]||##gray|//none//##||import “strings” _
_
hbar := strings.Repeat(“-”, 80)||import java.util.Arrays; _
_
char[] a = new char[80]; _
Arrays.fill(a, ‘-’); _
String s = new String(a);||
||# extract-substr[#extract-substr-note extract substring]||char target[3]; _
char source = “hello”; _
_
strncpy(target, source + 2, 2); _
target[2] = ‘\0’; _
_
##gray|/ also wcsncpy */##||"hello”[2:4]||"hello”.substring(2,4)||
||# index-substr[#index-substr-note index of substring]||const char *s = “hello”; _
const char p = strstr(“hello”, “ll”); _
size_t idx = p ? p - s : -1; _
_
##gray|/ also wcsstr */##||import “strings” _
_
##gray|@@//@@ zero-based index; -1 if not found:## _
strings.Index(“hello”, “ll”)||"hello”.indexOf(“ll”)||
||# fmt-str[#fmt-str-note format string]||char buf[100]; _
snprintf(buf, 100, “%s: %d”, “Spain”, 7); _
_
wchar_t buf2[100]; _
swprintf(buf2, 100, L”%S: %d”, L"Spain”, 7);||buf := fmt.Sprintf(“%s: %d”, “Spain”, 7)||String.format(“%s: %d”, “Spain”, 7)||
||# translate-case[#translate-case-note translate case] _
_
##gray|//to upper, to lower//##||char s = strdup(“hello”); _
int i; _
_
for (i=0; i < strlen(s); ++i) _
@< >@s[i] = toupper(s[i]); _
_
for (i=0; i < strlen(s); i++) _
@< >@s[i] = tolower(s[i]); _
_
##gray|/ also towupper and towlower */##||import “strings” _
_
strings.ToUpper(“hello”) _
strings.ToLower(“HELLO”)||"hello”.toUpperCase() _
“HELLO”.toLowerCase()||
||# trim[#trim-note trim] _
##gray|//both sides, on left, on right//##||char s = strdup(“ lorem “); _
size_t i, j; _
_
##gray|/ trim left /## _
for (i = 0; s[i] && isspace(s[i]); ++i); _
if (i) _
@< >@for (size_t j = 0; j < strlen(s) - i + 1; ++j) _
@< >@@< >@s[j] = s[j + i]; _
_
##gray|/ trim right /## _
for (i = strlen(s) - 1; s[i] && isspace(s[i]); –i); _
s[i + 1] = ‘\0’; _
_
##gray|/ also iswspace /##||import “strings” _
_
s := “ lorem “ _
strings.Trim(s, “ “) _
strings.TrimLeft(s, “ “) _
strings.TrimRight(s, “ “)||” hello “.trim()||
||# pad[#pad-note pad]||char buf[100]; _
_
##gray|/ pad right: /## _
snprintf(buf, 100, “%-10s”, “hello”); _
##gray|/ pad left: /## _
snprintf(buf, 100, “%10s”, “hello”); _
_
##gray|/ also swprintf */##||right_pad := fmt.Sprintf(“%-10s\n”, “hello”) _
left_pad := fmt.Sprintf(“%10s\n”, “hello”)|| ||
||# str-len[#str-len-note length] _
@< >@||strlen(“hello”) _
wcslen(L"hello”)||s := “αλφα” _
_
char_length := 0 _
##gray|@@//@@ iterate over characters, setting i to index and rune_val _
@@//@@ to Unicode point. Bad bytes get code point 0xFFFD:## _
for i, rune_val := range s { _
@< >@fmt.Printf(“%d %d\n”, i, rune_val) _
@< >@char_length += 1 _
} _
_
fmt.Printf(“bytes: %d chars: %d\n”, len(s), char_length)||String s = “hello”; _
int i = s.length();||
||# char-type[#char-type-note character type]||char _
wchar_t||byte _
rune||char _
Character||
||# char-literal[#char-literal-note character literal]||’A’ _
L’A’||##gray|//none//##||char n = ‘X’;||
||# char-lookup[#char-lookup-note character lookup]||"lorem ipsum”[6] _
L"lorem ipsum”[6]||##gray|@@//@@ 7th byte:## _
“lorem ipsum”[6] _
_
##gray|@@//@@ 7th char:## _
s := “αλφα βητα” _
var ch rune _
for i, rune_val := range s { _
@< >@if i == 6 { _
@< >@@< >@ch = rune_val _
@< >@} _
}|| ||
||# char-index[#char-index-note character index]||char *s = “aaa bbb ccc”; _
char p; _
size_t n; _
_
p = strchr(s, ‘ ‘); _
if (p) _
@< >@printf(“first space at %ld\n”, p - s); _
p = strrchr(s, ‘ ‘); _
if (p) _
@< >@printf(“last space at %ld\n”, p - s); _
_
n = strspn(s, “abc”); _
printf(“first %ld chars in set\n”, n); _
p = strpbrk(s, “ ,:.”); _
printf(“first %ld chars not in set\n”, n); _
_
##gray|/ also: wcschr wcsrchr wcsspn wcspbrk /##|| || ||
||# char-tests[#char-tests-note character tests]||#include _
#include _
_
isascii(ch) _
isrune(ch) _
iscntrl(ch) _
isgraph(ch) _
isalpha(ch) _
isspace(ch) _
isupper(ch) _
islower(ch) _
isalnum(ch) _
isdigit(ch) _
isxdigit(ch) _
ispunct(ch) _
_
##gray|/ also: iswascii, iswrune, @@…@@ /##||import “unicode” _
_
unicode.IsControl(ch) _
unicode.IsGraphic(ch) _
unicode.IsLetter(ch) _
unicode.IsSpace(ch) _
unicode.IsUpper(ch) _
unicode.IsLower(ch) _
unicode.IsDigit(ch) _
unicode.IsPunct(ch)|| ||
||# chr-ord[#chr-ord-note chr and ord]||##gray|/ Character types are integer types so no conversion is necessary. Use %c and %C to print a character like a string of length one. /## _
char ch = ‘A’; _
wchar_t ch2 = L’A’; _
_
int i = ch + 7; _
int i2 = ch2 + 7; _
_
wprintf(L”%c %d %C %d\n”, ch, ch, ch2, ch2);||##gray|/ Character types are integer types so no conversion is necessary. Use %c to print a character like a string of length one. /## _
_
fmt.Printf(“lambda: %c\n”, 0x3bb)|| ||
||||||||~ # regexes[#regexes-note regular expressions]||
||~ ||~ c||~ go||~ java||
||# regex-metachar[#regex-metachar-note metacharacters]||##gray|/ REG_BASIC: */## _
. [ ] \ * ^ $ _
_
##gray|/* REG_EXTENDED: */## _
. [ ] \ ( ) * + ? { } | ^ $||. [ ] \ ( ) * + ? { } | ^ $ _
_
##gray|//use raw string (i.e. backtick) literals to avoid having to escape backslashes.//##|| ||
||# char-class-abbrev[#char-class-abbrev-note character class abbrevations]||##gray|/* matches any character; does not match newline if _
@< >@REG_NEWLINE is used: /## _
. _
_
##gray|/ more character classes available in pcre library /##||. \d \D \s \S \w \W|| ||
||# regex-anchors[#regex-anchors-note anchors]||##gray|/ match beginning and end of string; match beginning and _
@< >@end of line if REG_NEWLINE is used: */## _
^ $||^ $ \A \b \B \z|| ||
||# regex-test[#regex-test-note match test]||#include _
_
regex_t rx; _
int retval; _
char *pat = “1999”; _
char s = “It’s 1999”; _
_
##gray|/ Use REG_NOSUB if 4th arg to regexec() is NULL /## _
if (retval = regcomp(&rx, pat, REGEXTENDED | REGNOSUB)) { _
@< >@char buf[200]; _
@< >@regerror(retval, &rx, buf, 200); _
@< >@fprintf(stderr, “regex error: %s\n”, buf); _
} else { _
@< >@if (regexec(&rx, s, 0, NULL, 0) == 0) _
@< >@@< >@printf(“Party!\n”); _
@< >@regfree(&rx); _
}||import “regexp” _
_
var rx = regexp.MustCompile(“1999”) _
if (rx.MatchString(“It’s 1999.”)) { _
@< >@fmt.Println(“Party!”) _
}||boolean isMatch = “hello”.matches(“.ll.*”);||
||# case-insensitive-regex[#case-insensitive-regex-note case insensitive match test]||#include _
_
regex_t rx; _
int retval; _
char *pat = “lorem”; _
char s = “Lorem”; _
_
if (retval = regcomp(&rx, pat, REGEXTENDED | REGICASE)) { _
@< >@char buf[200]; _
@< >@regerror(retval, &rx, buf, 200); _
@< >@fprintf(stderr, “Regex error: %s\n”, buf); _
} else { _
@< >@if (regexec(&rx, s, 0, NULL, 0) == 0) _
@< >@@< >@printf(“case insensitive match\n”); _
@< >@regfree(&rx); _
}||import “regexp” _
_
var rx = regexp.MustCompile(“(?i)lorem”) _
if (rx.MatchString(“Lorem Ipsum”)) { _
@< >@fmt.Println(“case insensitive match”) _
}|| ||
||# regex-modifiers[#regex-modifiers-note modifiers]||##gray|/ bit flags used in 3rd arg of regcomp(): */## _
REG_BASIC _
REG_EXTENDED _
REG_ICASE _
REG_NOSUB _
REG_NEWLINE||##gray|@@//@@ use (?i), (?m), @@…@@ to insert in regex:## _
i m s U|| ||
||# subst[#subst-note substitution]|| ||import “regexp” _
_
s := “do re mi mi mi” _
var rx = regexp.MustCompile(“mi”) _
fmt.Println(rx.ReplaceAllString(s, “ma”))||String s1 = “hello”.replace(“ll”,"LL”); _
String s2 = “hello”.replaceAll(“l”,"L”);||
||# group-capture[#group-capture-note group capture]||#include _
_
regex_t rx; _
int retval; _
char *pat = “([0-9]{4})-([0-9]{2})-([0-9]{2})”; _
char s = “2010-06-03”; _
_
if (retval = regcomp(&rx, pat, REG_EXTENDED)) { _
@< >@char buf[200]; _
@< >@regerror(retval, &rx, buf, 200); _
@< >@fprintf(stderr, “Regex error: %s\n”, buf); _
} else { _
@< >@##gray|/ first match is entire pattern /## _
@< >@regmatch_t matches[4]; _
@< >@if (regexec(&rx, s, 4, matches, 0) == 0) { _
@< >@@< >@char yr[5]; _
@< >@@< >@regmatch_t rm = matches[1]; _
@< >@@< >@##gray|/ rmso and rmeo contain index of start and end of _
@< >@@< >@@< >@match; they are set to -1 if unused /## _
@< >@@< >@strncpy(yr, s + rm.rmso, rm.rmeo - rm.rm_so); _
@< >@@< >@yr[5] = ‘\0’; _
@< >@@< >@printf(“year is %s\n”, yr); _
@< >@} _
@< >@regfree(&rx); _
}|| || ||
||||||||~ # dates-time[#dates-time-note dates and time]||
||~ ||~ c||~ go||~ java||
||# unix-epoch-type[#unix-epoch-type-note unix epoch type] _
@< >@||timet||int64||long||
||# broken-down-datetime-type[#broken-down-datetime-type-note broken-down datetime type]||struct tm||Time||java.util.Date||
||# current-unix-epoch[#current-unix-epoch-note current unix epoch]||timet now; _
_
if (time(&now) == -1) _
@< >@perror(“time failed”);||import “time” _
_
t := time.Now().Unix()||long epoch = System.currentTimeMillis() / 1000;||
||# current-datetime[#current-datetime-note current datetime]|| ||import “time” _
_
dt := time.Now()||import java.util.Date; _
_
long millis = System.currentTimeMillis(); _
Date dt = new Date(millis);||
||# broken-down-datetime-to-unix-epoch[#broken-down-datetime-to-unix-epoch-note broken-down datetime to unix epoch]||##gray|/ use host local time as tz: /## _
time_t t = mktime(&dt); _
_
##gray|/ use UTC as tz: /## _
time_t t2 = timegm(&dt2);||t := dt.Unix()||long epoch = dt.getTime() / 1000;||
||# unix-epoch-to-broken-down-datetime[#unix-epoch-to-broken-down-datetime-note unix epoch to broken-down datetime]||struct tm dt, dt2; _
_
if (!localtime_r(&now, &dt)) _
@< >@perror(“localtime_r failed”); _
_
##gray|/ UTC: */## _
if (!gmtime_r(&now, &dt2)) _
@< >@perror(“gmtime_r failed”);||var t int64 = 1421929926 _
var ns int64 = 0 _
dt := time.Unix(t, ns)||Date dt2 = new Date(epoch * 1000);||
||# fmt-datetime[#fmt-datetime-note format datetime]||char buf[100]; _
char *fmt = “%Y-%m-%d %H:%M:%S”; _
_
if (!strftime(buf, 100, fmt, &dt)) _
@< >@fputs(“strftime failed\n”, stderr);||layout := “2006-01-02 15:04:05” _
_
fmt.Println(dt.Format(layout))||String s = “yyyy-MM-dd HH:mm:ss”; _
DateFormat fmt = new SimpleDateFormat(s); _
String s2 = fmt.format(dt);||
||# parse-datetime[#parse-datetime-note parse datetime]||char *s = “1999-09-10 23:30:00”; _
char *fmt = “%Y-%m-%d %H:%M:%S”; _
char p = strptime(s, fmt, &dt3); _
if (!p) _
@< >@fputs(“strptime failed\n”, stderr);||layout := “2006-01-02:15:04:05” _
_
dt, err := time.Parse(layout, “1999-09-10 23:30:00”)||String s = “2011-05-03 17:00:00”; _
Date dt2 = fmt.parse(s);||
||# date-subtraction[#date-subtraction-note date subtraction]||##gray|/ use mktime for local; timegm for utc: */## _
double delta_sec = difftime(mktime(&dt), mktime(&dt2));||var delta time.Duration _
_
delta = dt.Sub(dt2)||##gray|//difference in milliseconds as a long://## _
dt2.getTime() - dt.getTime()||
||# add-duration[#add-duration-note add duration]||dt.tm_sec += 1000; _
mktime(&dt); _
_
dt.tm_hour += 1000; _
mktime(&dt); _
_
dt.tm_mday += 1000; _
mktime(&dt);||dt2 := dt + 1000 * time.Second _
dt3 := dt + 1000 * time.Hour||long day_ms = 24 * 3600 * 1000; _
Date dt = new Date(dt.getTime() + dayms));||
||# date-parts[#date-parts-note date parts]||int yr = dt.tmyear + 1900; _
int mo = dt.tm_mon + 1; _
int dy = dt.tm_mday;||yr := dt.Year() _
var mo time.Month = dt2.Month() _
dy := dt.Day()||import java.util.Date; _
import java.util.Calendar; _
import java.util.GregorianCalendar; _
_
Date dt = new Date(); _
GregorianCalendar cal = new GregorianCalendar(); _
cal.setTime(dt); _
_
cal.get(Calendar.YEAR) _
cal.get(Calendar.MONTH) + 1 _
cal.get(Calendar.DAYOFMONTH)||
||# time-parts[#time-parts-note time parts]||int hr = dt.tm_hour; _
int mi = dt.tm_min; _
int ss = dt.tm_sec;||hr := dt.Hour() _
mi := dt.Minute() _
ss := dt.Second()||import java.util.Date; _
import java.util.Calendar; _
import java.util.GregorianCalendar; _
_
Date dt = new Date(); _
GregorianCalendar cal = new GregorianCalendar(); _
cal.setTime(dt); _
_
cal.get(Calendar.HOUROFDAY) _
cal.get(Calendar.MINUTE) _
cal.get(Calendar.SECOND)||
||# build-datetime[#build-datetime-note build broken-down datetime]||dt.tm_year = 1999 - 1900; _
dt.tm_mon = 9 - 1; _
dt.tm_mday = 10; _
dt.tm_hour = 23; _
dt.tm_min = 30; _
dt.tm_sec = 0; _
dt.tm_isdst = 1; _
dt.tm_gmtoff = -7 * 60 * 60; _
_
if (mktime(&dt) == -1) _
@< >@fputs(“mktime failed\n”, stderr);||import “time” _
_
yr := 1999 _
var mo time.Month = 9 _
dy, hr, mi, ss, ns := 10, 23, 30, 0, 0 _
loc, _ := time.LoadLocation(“Local”) _
_
dt := time.Date(yr, mo, dy, hr, mi, ss, ns, loc)||import java.util.GregorianCalendar; _
_
int yr = 2015, mo = 5, dy = 31; _
int hr = 9, mi = 0, ss = 0; _
GregorianCalendar cal = _
@< >@new GregorianCalendar(yr, mo - 1, dy, hr, mi, ss); _
Date dt = cal.getTime();||
||# local-tmz-determination[#local-tmz-determination-note local time zone determination]||##gray|//On a Unix system, the local time zone is stored in /etc/localtime. A process can have a different local time zone by setting the TZ environment variable.//##|| || ||
||# tmz-info[#tmz-info-note time zone info] _
##gray|//name and utc offset in hours//##||##gray|//offset abbreviation://## _
dt.tm_zone _
_
##gray|//UTC offset in hours://## _
dt.tmgmtoff / 3600.0||name, offsetsec := dt.Zone() _
_
##gray|//offset abbreviation://## _
name _
_
##gray|//UTC offset in hours://## _
offset_sec / 3600.0|| ||
||# daylight-savings-test[#daylight-savings-test-note daylight savings test] _
@< >@||dt.tm_isdst|| || ||
||# microseconds[#microseconds-note microseconds]||#include _
_
struct timeval t; _
_
if (gettimeofday(&t, NULL) == -1) _
@< >@perror(“gettimeofday failed”); _
else _
@< >@printf(“epoch: %lu usec: %u\n”, t.tvsec, t.tvusec);||dt.Nanosecond() / 1000|| ||
||||||||~ # fixed-length-arrays[#fixed-length-arrays-note fixed-length arrays]||
||~ ||~ c||~ go||~ java||
||# declare-array[#declare-array-note declare]||int a[10];||##gray|@@//@@ values are zero-initialized:## _
var a [10]int|| ||
||# allocate-array-on-stack[#allocate-array-on-stack-note allocate on stack]||##gray|/* contents of memory undefined: /## _
int a[10];||##gray|//compiler decides location in memory//##||##gray|//none//##||
||# allocate-array-on-heap[#allocate-array-on-heap-note allocate on heap]||#include _
_
##gray|/ memory zero-initialized: */## _
int *a = calloc(10, sizeof *a);||##gray|//compiler decides location in memory//##||##gray|//all arrays allocated on heap//##||
||# free-array-on-heap[#free-array-on-heap-note free heap] _
@< >@||free(a);||##gray|//none; garbage collected//##||##gray|//none; garbage collected//##||
||# array-literal[#array-literal-note literal] _
@< >@||int a[] = {1, 2, 3};||##gray|//none//##|| ||
||# array-size[#array-size-note size] _
@< >@||sizeof(a) / sizeof(a[0])||len(a)|| ||
||# array-lookup[#array-lookup-note lookup] _
@< >@||a[0]||a[0]|| ||
||# array-update[#array-update-note update] _
@< >@||a[0] = 4;||a[0] = 4|| ||
||# array-out-of-bounds[#array-out-of-bounds-note out-of-bounds behavior]||##gray|//undefined, possible SIGSEGV//##||##gray|panic: index out of range## _
_
##gray|//if compiler detects a problem the code won’t compile//##|| ||
||# array-element-index[#array-element-index-note element index]||char *a[3] = {"foo”, “bar”, “baz”}; _
int loc = -1, i; _
_
for (i = 0; i < 3; ++i) { _
@< >@if (strcmp(“bar”, a[i]) == 0) { _
@< >@@< >@loc = i; _
@< >@@< >@break; _
@< >@} _
}||var a [3]string _
a[0] = “foo” _
a[1] = “bar” _
a[2] = “baz” _
loc := -1 _
_
for i, val := range a { _
@< >@if val == “bar” { _
@< >@@< >@loc = i _
@< >@} _
}|| ||
||# copy-array[#copy-array-note copy]||int a[3] = {1, 2, 3}; _
int b[3]; _
_
memcpy(b, a, sizeof(a));||a := []int{1, 2, 3} _
_
a2 := a _
##gray|@@//@@ also sets a[0] to 4:## _
a2[0] = 4 _
_
a3 := make([]int, len(a)) _
copy(a3, a) _
##gray|@@//@@ a[0] is unchanged:## _
a3[0] = 5|| ||
||# iterate-over-array[#iterate-over-array-note iterate over elements]||int a[10]; _
_
for (i = 0; i < 10; ++i ) { _
@< >@a[i] = i * i; _
}||var a [10]int _
_
for i, _ := range a { _
@< >@a[i] = i * i _
} _
for _, num := range a { _
@< >@fmt.Printf(“%d\n”, num) _
}|| ||
||# sort-array[#sort-array-note sort]||int _
compare(const void *a, const void b) { _
@< >@if ((int *)a < *(int )b) { _
@< >@@< >@return -1; _
@< >@} _
@< >@@< >@else if ((int *)a == *(int )b) { _
@< >@@< >@return 0; _
@< >@} _
@< >@else { _
@< >@@< >@return 1; _
@< >@} _
} _
_
int a[5] = {6, 8, 10, 9, 7}; _
_
##gray|/ 2nd arg is array length; 3rd arg is element size */## _
qsort(a, 5, sizeof (int), &compare);||##gray|//convert to resizable array//##|| ||
||||||||~ # resizable-arrays[#resizable-arrays-note resizable arrays]||
||~ ||~ c||~ go||~ java||
||# declare-resizable-array[#declare-resizable-array-note declare]|| ||##gray|@@//@@ Resizable arrays are called slices. _
@@//@@ To declare a slice instead of a fixed-length array, _
@@//@@ omit the length from the type:## _
var a []int _
##gray|@@//@@ slice of length 5; capacity 10:## _
a = make([]int, 5, 10)|| ||
||# resizable-array-literal[#resizable-array-literal-note literal] _
@< >@|| ||a := []int{1, 2, 3}|| ||
||# resizable-array-size[#resizable-array-size-note size] _
@< >@|| ||len(a) _
_
##gray|@@//@@ number of elements that can be stored in allocated memory; _
@@//@@ runtime reallocates when needed:## _
cap(a)||vec.size()||
||# resizable-array-lookup[#resizable-array-lookup-note lookup] _
@< >@|| ||a[0]||vec.elementAt(0)||
||# resizable-array-update[#resizable-array-update-note update] _
@< >@|| ||a[0] = 4|| ||
||# resizable-to-fixed[#resizable-to-fixed-note resizable to fixed array]|| ||resizable := []int{1, 2, 3} _
var fixed [3]int _
copy(fixed[:], resizable)|| ||
||# fixed-to-resizable[#fixed-to-resizable-note fixed to resizable array]|| ||var resizable2 []int _
resizable2 = fixed[:]|| ||
||# resizable-array-out-of-bounds[#resizable-array-out-of-bounds-note out-of-bounds behavior] _
@< >@|| ||##gray|//Both lookups and updates cause panics when out-of-bounds//##||##gray|//throws//## ArrayIndexOutOfBoundsException||
||# resizable-array-element-index[#resizable-array-element-index-note element index]|| ||a := []string{"foo”, “bar”, “baz”} _
loc := -1 _
_
for i, val := range a { _
@< >@if val == “bar” { _
@< >@@< >@loc = i _
@< >@} _
}|| ||
||# slice-resizable-array[#slice-resizable-array-note slice]|| ||a := []string{"a”, “b”, “c”, “d”, “e”} _
_
##gray|@@//@@ {"c”, “d”}:## _
a2 := a[2:4]|| ||
||# slice-resizable-array-to-end[#slice-resizable-array-to-end-note slice to end]|| ||a := []string{"a”, “b”, “c”, “d”, “e”} _
_
##gray|@@//@@ {"c”, “d”, “e”}:## _
a2 := a[2:]|| ||
||# resizable-array-back[#resizable-array-back-note manipulate back]|| ||a := []int{1, 2, 3} _
_
a = append(a, 4) _
num := a[len(a) - 1] _
a = a[:len(a) - 1]||vec.add(“hello”); _
##gray|//or//## _
vec.add(vec.size(), “hello”); _
vec.removeElementAt(vec.size()-1);||
||# resizable-array-front[#resizable-array-front-note manipulate front]|| ||a := []int{1, 2, 3} _
_
a = append([]int{0}, a@@…@@) _
num := a[0] _
a = a[1:]|| ||
||# concatenate-resizable-array[#concatenate-resizable-array-note concatenate]|| ||a := []int{1, 2, 3} _
a2 := []int{4, 5, 6} _
a3 := append(a, a2@@…@@)|| ||
||# copy-resizable-array[#copy-resizable-array-note copy]|| ||a := []int{1, 2, 3} _
_
a2 := a _
##gray|@@//@@ also sets a[0] to 4:## _
a2[0] = 4 _
_
a3 := make([]int, len(a)) _
copy(a3, a) _
##gray|@@//@@ a[0] is unchanged:## _
a3[0] = 5|| ||
||# iterate-over-resizable-array[#iterate-over-resizable-array-note iterate over elements]|| ||a := []string{"do”, “re”, “mi”} _
for _, s := range(a) { _
@< >@fmt.Printf(“value: %s\n”, s) _
}||for ( String s : vec ) { _
@< >@##gray|//do something with s//## _
}||
||# iterate-indices-elem[#iterate-indices-elem-note iterate over indices and elements]|| || a := []string{"do”, “re”, “mi”} _
for i, s := range(a) { _
@< >@fmt.Printf(“value at %d: %s\n”, i, s) _
}|| ||
||# reverse-resizable-array[#reverse-resizable-array-note reverse]|| ||import “sort” _
_
a := []int{1, 2, 3} _
sort.Sort(sort.Reverse(sort.IntSlice(a)))|| ||
||# sort-resizable-array[#sort-resizable-array-note sort]|| ||unsortedInts := []int{3, 1, 4, 2} _
sortedInts := sort.IntSlice(unsortedInts) _
sort.Sort(sortedInts) _
##gray|@@//@@ sortedInts is now []int{1, 2, 3, 4}## _
_
floats := []float64{3.0, 1.0, 4.0, 2.0} _
sort.Float64s(floats) _
##gray|@@//@@ floats is now []float64{1.0, 2.0, 3.0, 4.0}## _
_
strs := []string{"b”, “a”, “d”, “c”} _
sort.Strings(strs) _
##gray|@@//@@ strs is now []string{"a”, “b”, “c”, “d”}##|| ||
||||||||~ # dictionaries[#dictionaries-note dictionaries]||
||~ ||~ c||~ go||~ java||
||# declare-dict[#declare-dict-note declare] _
@< >@|| ||d := make(map[string]int)|| ||
||# dict-literal[#dict-literal-note literal] _
@< >@|| ||d := map[string]int {"t”: 1, “f”: 0}|| ||
||# dict-size[#dict-size-note size] _
@< >@|| ||len(d)||m.size()||
||# dict-lookup[#dict-lookup-note lookup] _
@< >@|| ||d[“t”]||m.put(“hello”, 5); _
m.get(“hello”)||
||# dict-update[#dict-update-note update] _
@< >@|| ||d[“t”] = 2|| ||
||# dict-missing-key[#dict-missing-key-note missing key behavior] _
@< >@|| ||##gray|//returns zero value for value type//##||null||
||# dict-is-key-present[#dict-is-key-present-note is key present]|| ||##gray|@@//@@ If key not present, val will contain _
@@//@@ zero value for type and ok will contain false:## _
val, ok = d[“y”]]|| ||
||# dict-delete[#dict-delete-note delete] _
@< >@|| ||delete(d, “f”)||m.remove(“hello”);||
||# dict-iter[#dict-iter-note iterate]|| ||for k, v := range d { _
@< >@fmt.Printf(“%s: %d\n”, k, v) _
}||for ( java.util.Map.Entry e : m.entrySet() ) { _
@< >@##gray|//use e.getKey() or e.getValue()//## _
}||
||||||||~ # functions[#functions-note functions]||
||~ ||~ c||~ go||~ java||
||# std-file-handles[#std-file-handles-note standard file handles]||stdin stdout stderr||import “os” _
_
os.Stdin os.Stdout os.Stderr||System.in _
System.out _
System.err||
||# read-line-stdin[#read-line-stdin-note read line from stdin]||char line = NULL; _
size_t cap = 0; _
ssize_t len; _
_
##gray|/ if line is not NULL, it should be memory allocated by _
@< >@malloc and the size should be in cap. If size is not _
@< >@sufficient getline will call realloc on line /## _
len = getline(&line, &cap, stdin); _
_
if (len == -1) { _
@< >@if (ferror(stdin)) { _
@< >@@< >@perror(“getline err”); _
@< >@} _
@< >@else if (feof(stdin)) { _
@< >@@< >@fprintf(stderr, “end of file\n”); _
@< >@} _
} else { _
_
@< >@##gray|/ use line here /## _
_
@< >@free(line); _
}||import “bufio” _
import “os” _
_
var line string _
var err error _
_
b := bufio.NewReader(os.Stdin) _
_
line, err = b.ReadString(‘\n’) _
_
if err != nil { _
@< >@os.Stderr.WriteString(“error!”) _
} else { _
@< >@##gray|@@//@@ use line here## _
}|| ||
||# write-line-stdout[#write-line-stdout-note write line to stdout]||##gray|/ returns EOF on error /## _
int retval = puts(“Hello, World!”);||import “os” _
_
os.Stdout.WriteString(“Hello, World!\n”)|| ||
||# printf[#printf-note write formatted string to stdout] _
@< >@||printf(“count: %d\n”, 7); _
wprintf(L"count: %d\n”, 7);||fmt.Printf(“count: %d\n”, 7)||System.out.printf(“count: %d”, 7);||
||# open-file[#open-file-note open file for reading]||##gray|/ returns NULL on error */## _
FILE f = fopen(“/etc/hosts”, “r”);||import “os” _
_
raw, err := os.Open(“/etc/hosts”) _
if err == nil { _
@< >@f := bufio.NewReader(raw) _
}|| ||
||# open-file-write[#open-file-write-note open file for writing]||##gray|/ returns NULL on error */## _
FILE f = fopen(“/tmp/test”, “w”);||import “os” _
_
perms := os.ORDWR | os.OCREATE _
f, err := os.OpenFile(“/tmp/test”, perms, 0644)|| ||
||# open-file-append[#open-file-append-note open file for appending]||##gray|/ returns NULL on error */## _
FILE f = fopen(“/tmp/err.log”, “a”);||import “os” _
_
perms := os.ORDWR | os.OCREATE | os.O_APPEND _
f, err := os.OpenFile(“/tmp/test”, perms, 0644)|| ||
||# close-file[#close-file-note close file]||##gray|/ returns EOF on error /## _
int retval = fclose(f);||err := f.Close()|| ||
||# io-err[#io-err-note i/o errors]||##gray|//Functions return values such as// EOF, NULL, //or// -1 //to indicate error. Some functions return the value of// errno. //In some cases errors are not distinguished from end-of-file. The functions// ferror() //and// feof() //can be used to test a file handle. _
_
The type of error is stored in// errno. strerror(errno) //or the thread safe// strerror_r(errno, buf, buflen) //convert the errors code to a string and// perror() //writes its argument to// stderr //with// sterror(errno).##|| || ||
||# read-line[#read-line-note read line]||char line[BUFSIZ]; _
_
if (fgets(line, BUFSIZ, f) == NULL) { _
@< >@if (ferror(stdin)) { _
@< >@@< >@perror(“getline err”); _
@< >@} _
@< >@else if (feof(stdin)) { _
@< >@@< >@fprintf(stderr, “end of file\n”); _
@< >@} _
_
} else { _
@< >@if (‘\n’ == line[strlen(line) - 1]) { _
_
@< >@@< >@##gray|/ use line here /## _
_
} else { _
@< >@@< >@fprintf(stderr, “long line truncated\n”); _
}|| || ||
||# file-line-iterate[#file-line-iterate-note iterate over file by line]|| || || ||
||# read-file-array[#read-file-array-note read file into array of strings]|| || || ||
||# read-file-str[#read-file-str-note read file into string]|| || || ||
||# write-str[#write-str-note write string]||##gray|/ returns EOF on error /## _
int retval = fputs(“Hello, World!”, f);||bytes_written, err := f.WriteString(“Hello, World!”) _
_
bytes_written, err := f.Write(byte)|| ||
||# write-line[#write-line-note write line]||##gray|/ returns EOF on error /## _
int retval = fputs(“Hello, World!\n”, f);||bytes_written, err := f.WriteString(“Hello, World!\n”) _
_
bytes_written, err := f.Write(byte)|| ||
||# flush[#flush-note flush file handle]||if (fflush(f) == EOF) { _
@< >@perror(“fflush failed”); _
}||err := f.Sync()|| ||
||# eof-test[#eof-test-note end-of-file test] _
@< >@||feof(f)|| || ||
||# seek[#seek-note get and set file handle position]||long pos; _
if ((pos = ftell(f)) == -1) { _
@< >@perror(“ftell failed”); _
} _
_
##gray|/ 3rd arg can also be SEEKCUR or SEEKEND /## _
if (fseek(f, 0, SEEK_SET) == -1) { _
@< >@perror(“fseek failed”); _
}|| || ||
||# tmp-file[#tmp-file-note open unused file]||#include @< >@##gray|/ PATH_MAX /## _
#include _
_
char buf[PATH_MAX]; _
_
strcpy(buf, “/tmp/foo.XXXXXX”); _
_
##gray|/ terminal Xs will be replaced: */## _
int fd = mkstemp(buf); _
_
if (fd != -1) { _
@< >@FILE f = fdopen(fd, “w”); _
_
@< >@if (NULL == f) { _
@< >@@< >@perror(“fdopen failed”); _
@< >@} else { _
@< >@@< >@##gray|/ use f /## _
@< >@} _
_
} else { _
@< >@perror(“mkstemp failed”); _
}|| || ||
||||||||~ # files[#files-note files]||
||~ ||~ c||~ go||~ java||
||# file-test[#file-test-note file test, regular file test] _
@< >@||#include _
#include @< >@##gray|/ access() /## _
_
struct stat buf; _
_
if (access(“/tmp/foo”, F_OK) >= 0) { _
@< >@##gray|/ file exists /## _
} _
_
if (stat(“/tmp/foo”, &buf) != 0) { _
@< >@perror(“stat failed”); _
} else if (SISREG(buf.stmode)) { _
@< >@##gray|/ file is regular /## _
}||import “os” _
_
fi, err := os.Stat(“/tmp/foo”) _
if os.IsNotExist(err) { _
@< >@fmt.Printf(“Does not exit\n”) _
} else { _
@< >@fmt.Printf(“Exists\n”) _
@< >@fm := fi.Mode() _
@< >@if fm.IsRegular() { _
@< >@@< >@fmt.Printf(“Is Regular”) _
@< >@} else { _
@< >@@< >@fmt.Printf(“Is Not Regular”) _
@< >@} _
}||import java.io.File; _
_
File f = new File(“/etc/hosts”); _
f.exists() _
f.isFile()||
||# file-size[#file-size-note file size] _
@< >@||#include _
_
struct stat buf; _
_
if (stat(“/tmp/foo”, &buf) != 0) { _
@< >@perror(“stat failed”); _
} else { _
@< >@printf(“size: %llu\n”, buf.st_size); _
}||fi.Size()||import java.io.File; _
_
File f = new File(“/etc/hosts”); _
f.length()||
||# readable-writable-executable[#readable-writable-executable-note is file readable, writable, executable]||#include _
_
if (access(“/etc/hosts”, R_OK) != 0) { _
@< >@printf(“not readable\n”); _
} _
if (access(“/etc/hosts”, W_OK) != 0) { _
@< >@printf(“not writable\n”); _
} _
if (access(“/etc/hosts”, X_OK) != 0) { _
@< >@printf(“not executable\n”); _
}|| || ||
||# chmod[#chmod-note set file permissions]||#include _
_
if (chmod(“/tmp/foo”, 0755) == -1) { _
@< >@perror(“chmod failed”); _
}||import “os” _
_
err := os.Chmod(“/tmp/foo”, 0755) _
if err != nil { _
@< >@fmt.Printf(“Chmod failed\n”) _
}||import java.io.File; _
_
File f = new File(“/tmp/foo”); _
_
##gray|@@//@@ sets owner perms; to turn perms off _
@@//@@ set arg to false:## _
f.setReadable(true); _
f.setWritable(true); _
f.setExecutable(true); _
_
##gray|@@//@@ if 2nd arg is false, perms are _
@@//@@ for owner, group, and other:## _
f.setReadable(true, false); _
f.setWritable(true, false); _
f.setExecutable(true, false);||
||# last-modification-time[#last-modification-time-note last modification time]|| || || ||
||# file-cp-rm-mv[#file-cp-rm-mv-note copy file, remove file, rename file]||##gray|/ no copy function in standard library /## _
_
if (remove(“/tmp/foo”)) { _
@< >@perror(“remove failed”); _
} _
_
if (rename(“/tmp/bar”, “/tmp/foo”)) { _
@< >@perror(“rename failed”); _
}||import “os” _
_
##gray|@@//@@ no copy function in standard library## _
_
err := os.Remove(“/tmp/foo”) _
if err != nil { _
@< >@fmt.Printf(“Remove failed: %s\n”, err) _
} _
_
err2 := os.Rename(“/tmp/bar”, “/tmp/foo”) _
if err2 != nil { _
@< >@fmt.Printf(“Rename failed: %s\n”, err2) _
}||import java.io.File; _
_
##gray|//??//## _
_
File f2 = new File(“/tmp/foo”); _
f2.delete(); _
_
File f3 = new File(“/tmp/bar”); _
f3.renameTo(new File(“/tmp/bar”));||
||# symlink[#symlink-note create symlink, symlink test, readlink]||#include @< >@##gray|/ PATH_MAX /## _
#include _
#include _
_
if (symlink(“/etc/hosts”, “/tmp/hosts”) == -1) { _
@< >@perror(“symlink failed”); _
} _
_
struct stat sbuf; _
_
if (stat(“/tmp/hosts”, &buf) != 0) { _
@< >@perror(“stat failed”); _
} else if (SISLNK(buf.stmode)) { _
@< >@##gray|/ file is symlink /## _
} _
_
char pbuf[PATH_MAX + 1]; _
_
ssizet size = readlink(“/tmp/hosts”, pbuf, PATHMAX); _
_
if (size >= 0 ) { _
@< >@pbuf[size] = 0; _
@< >@##gray|/ pbuf now contains null-terminated string _
@< >@@< >@with target path /## _
}||import “os” _
_
err := os.Symlink(“/etc/hosts”, “/tmp/hosts”) _
if err != nil { _
@< >@fmt.Printf(“Symlink failed: %s\n”, err) _
} _
_
fi, err2 := os.Lstat(“/tmp/hosts”) _
if err2 == nil { _
@< >@fm := fi.Mode() _
@< >@if fm & os.ModeSymlink != 0 { _
@< >@@< >@fmt.Println(“File is a Symlink”) _
@< >@} _
} else { _
@< >@fmt.Printf(“Lstat failed: %s\n”, err2) _
} _
_
s, err3 := os.Readlink(“/tmp/hosts”) _
if err3 != nil { _
@< >@fmt.Printf(“Readlink failed: %s\n”, err3) _
} else { _
@< >@fmt.Printf(“Link target: %s\n”, s) _
}|| ||
||# unused-file-name[#unused-file-name-note generate unused file name]||##gray|/ if first argument is NULL, path is in system temp _
@< >@directory. Caller should free() return value. */## _
char *path = tempnam(“/tmp”, “foo”);||import “io/ioutil” _
_
##gray|@@//@@ Uses system tmp dir if 1st arg is empty string:## _
f, err := ioutil.TempFile(“/tmp”, “foo”) _
if err == nil { _
@< >@fmt.Printf(“writing to: %s\n”, f.Name()) _
@< >@f.WriteString(“foo content”) _
}|| ||
||||||||~ # file-fmt[#file-fmt-note file formats]||
||~ ||~ c||~ go||~ java||
||# parse-json[#parse-json-note parse json]|| ||import “encoding/json” _
_
type TruthTable struct { _
@< >@T int @@json:T@@ _
@< >@F int @@json:F@@ _
} _
_
bytes := []byte({"T": 1, "F": 0}) _
var truthTable TruthTable _
err := json.Unmarshal(bytes, &truthTable)|| ||
||# generate-json[#generate-json-note generate json]|| ||import “encoding/json” _
_
type TruthTable struct { _
@< >@T int @@json:T@@ _
@< >@F int @@json:F@@ _
} _
_
truthTable := TruthTable{T: 1, F: 0} _
bytes, err := json.Marshal(truthTable)|| ||
||||||||~ # directories[#directories-note directories]||
||~ ||~ c||~ go||~ java||
||# working-dir[#working-dir-note working directory]|| ||import “os” _
_
dir, err := os.Getwd() _
if err != nil { _
@< >@os.Stderr.WriteString(“Gtwd failed\n”) _
} else { _
@< >@fmt.Printf(“pwd: %s\n”, dir) _
} _
_
err2 := os.Chdir(“/tmp”) _
if err2 != nil { _
@< >@os.Stderr.WriteString(“Chdir failed\n”); _
}|| ||
||# build-pathname[#build-pathname-note build pathname]|| ||import “path” _
_
pathname := path.Join(“/etc”, “hosts”) _
fmt.Printf(“path: %s\n”, pathname)||import java.io.File; _
_
File root = File.listRoots()[0]; _
File etc = new File(root, “etc”); _
File hosts = new File(etc, “hosts”); _
String path = hosts.getPath();||
||# dirname-basename[#dirname-basename-note dirname and basename]||#include _
_
char *s1 = strdup(“/etc/hosts”); _
char s2 = strdup(“/etc/hosts”); _
##gray|/ Check whether s1 or s2 are NULL. /## _
_
##gray|/ Some implementations return pointers to statically allocated _
@< >@memory which is overwritten by subsequent calls; _
@< >@others modify the input string. */## _
char *s3 = dirname(s1); _
char *s4 = basename(s2);||import “path” _
_
path.Dir(“/etc/hosts”) _
path.Base(“/etc/hosts”)||import java.io.File; _
_
File f = new File(“/etc/hosts”); _
String dirname = f.getParent(); _
String basename = f.getName();||
||# absolute-pathname[#absolute-pathname-note absolute pathname]||char s; _
_
if ((s = realpath(“..”, NULL)) == NULL) { _
@< >@perror(“realpath failed”); _
} _
else { _
@< >@##gray|/ use s */## _
}|| ||import java.io.File; _
_
File f = new File(“foo”); _
String abspath = f.getAbsolutePath(); _
_
##gray|@@//@@ getCanonicalPath() expands .. and .:## _
File f2 = new File(“../foo”); _
String abspath2 = f2.getCanonicalPath(); _
File f3 = new File(“./foo”); _
String abspath3 = f3.getCanonicalPath();||
||# dir-iterate[#dir-iterate-note iterate over directory by file]||#include _
_
DIR *dir = opendir(“/etc”); _
struct dirent de; _
_
while (de = readdir(dir)) { _
@< >@printf(“%s\n”, de->d_name); _
} _
_
closedir(dir);||import “io/ioutil” _
_
a, err := ioutil.ReadDir(“/etc”) _
if err == nil { _
@< >@for _, fi := range a { _
@< >@@< >@fmt.Printf(“name: %s\n”, fi.Name()) _
@< >@} _
}|| ||
||# glob[#glob-note glob paths]||#include _
_
glob_t pglob; _
int i; _
_
glob(“/etc/”, 0, NULL, &pglob); _
_
for (i = 0; i < pglob.gl_pathc; ++i) { _
@< >@printf(“%s\n”, pglob.gl_pathv[i]); _
} _
_
globfree(&pglob);||import “path/filepath” _
_
a, err := filepath.Glob(“/etc/”) _
if err == nil { _
@< >@for _, path := range(a) { _
@< >@@< >@fmt.Printf(“path: %s\n”, path) _
@< >@} _
}|| ||
||# mkdir[#mkdir-note make directory]||#include _
_
if (mkdir(“/tmp/foo”)) { _
@< >@fprintf(stderr, “mkdir err: %s\n”, strerror(errno)); _
}||err := os.Mkdir(“/tmp/foo”, 0775) _
if err != nil { _
@< >@fmt.Printf(“Mkdir failed: %s\n”, err) _
}||import java.io.File; _
_
File f = new File(“/tmp/foo/bar”); _
f.mkdirs();||
||# recursive-cp[#recursive-cp-note recursive copy]|| || || ||
||# rmdir[#rmdir-note remove empty directory]||#include _
_
if (rmdir(“/tmp/foo”) == -1) { _
@< >@perror(“rmdir failed”); _
}||err := os.Remove(“/tmp/foo”) _
if err != nil { _
@< >@fmt.Printf(“Remove failed: %s”, err) _
}|| ||
||# rm-rf[#rm-rf-note remove directory and contents]|| ||err := os.RemoveAll(“/tmp/foo”) _
if err != nil { _
@< >@fmt.Printf(“RemoveAll failed: %s”, err) _
}|| ||
||# dir-test[#dir-test-note directory test] _
@< >@||#include _
_
struct stat buf; _
_
if (stat(“/tmp/foo”, &buf) != 0) { _
@< >@perror(“stat failed”); _
} else if (SISDIR(buf.stmode)) { _
@< >@##gray|/ file is directory /## _
}|| ||import java.io.File; _
_
File f = new File(“/tmp”); _
f.isDirectory()||
||# unused-dir[#unused-dir-note generate unused directory]||#include _
_
char buf[PATH_MAX]; _
_
strcpy(buf, “/tmp/fooXXXXXX”); _
_
##gray|/ terminal Xs will be replaced: /## _
if (mkdtemp(buf) == NULL) { _
@< >@perror(“mkdtemp failed”); _
} else { _
@< >@##gray|/ use buf /## _
}||import “io/ioutil” _
_
##gray|@@//@@ Uses system tmp dir if 1st arg is empty string:## _
path, err := ioutil.TempDir(“/tmp”, “foo”) _
if err == nil { _
@< >@fmt.Printf(“dir path: %s\n”, path) _
}|| ||
||# system-tmp-dir[#system-tmp-dir-note system temporary file directory]||##gray|/ defined in /## _
P_tmpdir||import “os” _
_
path := os.TempDir()|| ||
||||||||~ # processes-environment[#processes-environment-note processes and environment]||
||~ ||~ c||~ go||~ java||
||# cmd-line-arg[#cmd-line-arg-note command line arguments]||int main(int argc, char @@@@argv) { _
@< >@if (argc > 1) _
@< >@@< >@printf(“first arg: %s\n”, argv[1]); _
@< >@return 0; _
}||import “os” _
_
if len(os.Args) > 1 { _
@< >@fmt.Printf(“first arg: %\n”, os.Args[1]) _
}|| ||
||# program-name[#program-name-note program name]||int main(int argc, char @@*@@argv) { _
@< >@printf(“program name: %s\n”, argv[0]); _
@< >@return 0; _
}||import “os” _
_
fmt.Printf(“program name: %s\n”, os.Args[0])|| ||
||# env-var[#env-var-note environment variable]||#include _
_
char home = getenv(“HOME”); _
setenv(“EDITOR”, “emacs”, 1); _
unsetenv(“EDITOR”);||import “os” _
_
home := os.Getenv(“HOME”) _
_
err := os.Setenv(“EDITOR”, “emacs”) _
if err != nil { _
@< >@fmt.Printf(“Setenv failed: %s\n”, err) _
}|| ||
||# env-var-iter[#env-var-iter-note iterate over environment variables]||extern char @@@@environ; _
char @@*@@env, *p, *key; _
_
for (env = environ; env; ++env) { _
@< >@p = strchr(env, ‘=’); _
@< >@if (p) { _
@< >@@< >@size_t keylen = p - env; _
@< >@@< >@key = strndup(env, keylen); _
@< >@@< >@printf(“key: %s value: %s\n”, key, env + keylen + 1); _
@< >@@< >@free(key); _
@< >@} _
}||import “os” _
import “strings” _
_
for _, s := range os.Environ() { _
@< >@a := strings.SplitN(s, “=”, 2) _
@< >@fmt.Printf(“key: %s value: %s\n”, a[0], a[1]) _
}|| ||
||# user-id-name[#user-id-name-note get user id and name]||#include @< >@##gray|/ getlogin /## _
_
printf(“uid: %d\n”, getuid()); _
printf(“username: %s\n”, getlogin());||import “os” _
_
os.Getuid() _
##gray|/ username? /##|| ||
||# exit[#exit-note exit]||##gray|/ use 0 for success; 1 through 127 for failure /## _
exit(1);||import “os” _
_
os.Exit(1)|| ||
||# executable-test[#executable-test-note executable test]||#include _
_
if (access(“/bin/ls”, X_OK) != 0) { _
@< >@printf(“not executable\n”); _
}|| || ||
||# external-cmd[#external-cmd-note external command]||##gray|/ retval of -1 indicates fork or wait failed. _
@< >@127 indicates shell failed */## _
int retval = system(“ls -l “);|| || ||
||# fork[#fork-note fork]|| || || ||
||# exec[#exec-note exec]|| || || ||
||# pipe[#pipe-note pipe]|| || || ||
||# wait[#wait-note wait]|| || || ||
||# pid[#pid-note get pid, parent pid]||#include _
_
##gray|/ getpid() and getppid() have return type pid_t /## _
printf(“%d\n”, getpid()); _
printf(“%d\n”, getppid())||import “os” _
_
fmt.Println(os.Getpid()) _
fmt.Println(os.Getppid())|| ||
||# signal-handler[#signal-handler-note set signal handler]||#include _
_
##gray|/ assumes a POSIX environment /## _
void _
handle_signal(int signo) { _
@< >@int restore = errno; _
@< >@switch(signo) { _
@< >@case SIGUSR1: _
@< >@@< >@write(1, “caught SIGUSR1\n”, 15); _
@< >@@< >@break; _
@< >@default: _
@< >@@< >@break; _
@< >@} _
@< >@errno = restore; _
} _
_
##gray|/ 2nd arg can also be SIGIGN or SIGDFL /## _
sigt prevhandler = signal(SIGUSR1, &handle_signal); _
_
if (prevhandler == SIGERR) { _
@< >@perror(“signal failed”); _
@< >@exit(1); _
}|| || ||
||# send-signal[#send-signal-note send signal]||#include _
#include @< >@##gray|/ getppid /## _
_
if (kill(getppid(), SIGUSR1) == -1) { _
@< >@perror(“kill failed”); _
}|| || ||
||||||||~ # option-parsing[#option-parsing-note option parsing]||
||~ ||~ c||~ go||~ java||
||# getopt[#getopt-note getopt]||#include _
_
##gray|/ 2nd value indicates whether option takes an argument */## _
static struct option long_opts[] = { _
@< >@{"debug”, no_argument, NULL, ‘d’}, _
@< >@{"threshold”, required_argument, NULL, ‘t’}, _
@< >@{0, 0, 0, 0} _
}; _
_
int debug = 0; _
double threshold = 0.0; _
char *file = NULL; _
_
int ch; _
int opti; _
char endptr; _
_
while (1) { _
@< >@ch = getoptlong(argc, argv, “dt:”, longopts, &opti); _
@< >@if (-1 == ch) { _
@< >@@< >@break; _
@< >@} _
_
@< >@switch (ch) { _
@< >@case ‘d’: _
@< >@@< >@debug = 1; _
@< >@@< >@break; _
@< >@case ‘t’: _
@< >@@< >@threshold = strtod(optarg, &endptr); _
@< >@@< >@if (endptr != 0) { _
@< >@@< >@@< >@fprintf(stderr, “expected float: %s\n”, optarg); _
@< >@@< >@@< >@exit(1); _
@< >@@< >@} _
@< >@@< >@break; _
@< >@default: _
@< >@@< >@fprintf(stderr, “unexpected arg: %d\n”, ch); _
@< >@@< >@exit(1); _
@< >@} _
} _
_
##gray|/* optind is index of 1st arg not consumed by getopt /## _
if (optind != argc - 1) { _
@< >@fputs(“USAGE: foo [@@–@@multi] [@@–@@threshold=NUM] FILE\n”, _
@< >@@< >@@< >@@< >@stderr); _
@< >@exit(1); _
} _
else { _
@< >@file = argv[optind]; _
}||var debug bool _
var threshold int _
_
flag.BoolVar(&debug, “debug”, false, “debug mode”) _
flag.IntVar(&threshold, “threshold”, 100, “threshold value”) _
flag.Parse() _
_
##gray|@@//@@ e.g. could call executable with _
@@//@@ _
@@//@@@< >@@< >@-debug -threshold 200##|| ||
||||||||~ # libraries-namespaces[#libraries-namespaces-note libraries and namespaces]||
||~ ||~ c||~ go||~ java||
||# load-lib[#load-lib-note load library]||##gray|/ The library must also be linked: _
_
@< >@@< >@@< >@$ gcc foo.o main.c _
_
@< >@@< >@If the library is in an archive: _
_
@< >@@< >@@< >@$ gcc -lfoo main.c _
*/## _
#include “foo.h”||import “foo” _
_
##gray|@@//@@ Only capitalized identifiers are visible:## _
var bar = foo.GetBar()|| ||
||# load-lib-subdir[#load-lib-subdir-note load library in subdirectory]||#include “lib/foo.h”||import “lib/foo”|| ||
||# lib-path[#lib-path-note library path]||##gray|//Add directory to path searched by// #include //directive://## _
$ gcc -I/home/fred/include foo.c _
_
##gray|//Add directory to path searched by -l (lowercase L) option://## _
$ gcc -L/home/fred/lib -lbar foo.c||##gray|//The installation libraries are in the// GOROOT //directory. Additional directories can be listed in the// GOPATH //environment variable. The directories are separated by colons (semicolons) on Unix (Windows). _
_
Each directory contains a// src //subdirectory containing source code and potentially a// pkg/ARCH //subdirectory containing compiled libraries.//##|| ||
||# declare-namespace[#declare-namespace-note declare namespace]||##gray|//none//##||##gray|@@//@@ A package declaration must be first statement _
@@//@@ in every source file..## _
package foo|| ||
||# alias-namespace[#alias-namespace-note alias namespace] _
@< >@||##gray|//none//##||import fu “foo”|| ||
||# unqualified-import[#unqualified-import-note unqualified import of namespace]||##gray|//none//##||import . “foo”|| ||
||unqualified import of definitions|| || || ||
||# pkg-manager[#pkg-manager-note package manager] _
##gray|//search, install, list installed//##|| || || ||
||||||||~ # objects[#objects-note objects]||
||~ ||~ c||~ go||~ java||
||# def-class[#def-class-note define class]|| ||##gray|@@//@@ Methods can be defined for any Go type. _
@@//@@ Thus a type definition can be regarded as a class definition.## _
type Counter struct { _
@< >@value int _
}|| ||
||# create-object[#create-object-note create object] _
@< >@|| || cnt := Counter{value: 7}|| ||
||# def-method[#def-method-note define method]|| ||func (cnt Counter) Value() int { _
@< >@return cnt.value _
} _
_
##gray|@@//@@ receiver must be pointer if method modifies it:## _
func (cnt Counter) Incr() { _
@< >@cnt.value++ _
}|| ||
||# invoke-method[#invoke-method-note invoke method]|| ||##gray|@@//@@ same syntax for pointer and non-pointer receiver:## _
cnt.Incr()|| ||
||# subclass[#subclass-note subclass]|| ||##gray|@@//@@ An abstract superclass can be declared _
@@//@@ using the interface keyword:## _
type Incrementable interface { _
@< >@Incr() _
@< >@Value() int _
} _
_
func IncrAndPrint(incr Incrementable) { ) _
@< >@incr.Incr() _
@< >@fmt.Printf(“incr: %d\n”, incr.Value()) _
} _
_
cnt := Counter{value: 8} _
IncrAndPrint(&cnt)|| ||
||||||||~ # user-defined-types[#user-defined-types-note user-defined types]||
||~ ||~ c||~ go||~ java||
||# typedef[#typedef-note typedef]||typedef int customer_id; _
customerid cid = 3;||type customerid int _
_
var cid customer_id _
cid = 3||##gray|//none//##||
||# enum[#enum-note enum]||enum dayofweek { _
@< >@mon, tue, wed, thu, fri, sat, sun _
}; _
_
enum dayofweek dow = tue;|| ||public enum DayOfWeek { MON, TUE, WED, THU, FRI, SAT, SUN }; _
DayOfWeek d = DayOfWeek.TUE;||
||[#struct-definition struct definition]||struct medal_count { _
@< >@const char country; _
@< >@int gold; _
@< >@int silver; _
@< >@int bronze; _
};||type MedalCount struct { _
@< >@country string _
@< >@gold int _
@< >@silver int _
@< >@bronze int _
}|| ||
||[#struct-declaration struct declaration] _
@< >@||struct medalcount spain;|| || ||
||[#struct-initialization struct initialization]||struct medalcount spain = {"Spain”, 3, 7, 4}; _
_
struct medal_count france = { _
@< >@.gold = 8, _
@< >@.silver = 7, _
@< >@.bronze = 9, _
@< >@.country = “France” _
};||spain := MedalCount{"Spain”, 3, 2, 1} _
_
france := MedalCount{ _
@< >@bronze: 9, _
@< >@silver: 7, _
@< >@gold: 8, _
@< >@country: “France”}|| ||
||# struct-literal[#struct-literal-note struct literal]||struct medal_count france; _
_
france = (struct medal_count) { _
@< >@.gold = 8, _
@< >@.silver = 7, _
@< >@.bronze = 9, _
@< >@.country = “France” _
};|| || ||
||[#struct-member-assignment struct member assignment]||spain.country = “Spain”; _
spain.gold = 3; _
spain.silver = 7; _
spain.bronze = 4;||france := MedalCount{} _
france.country = “France” _
france.gold = 7 _
france.silver = 6 _
france.bronze = 5|| ||
||[#struct-member-access struct member access]||int spaintotal = spain.gold + spain.silver + spain.bronze;||francetotal = france.gold + _
@< >@france.silver + _
@< >@france.bronze|| ||
||||||||~ # cpp-macros[#cpp-macros-note c preprocessor macros]||
||~ ||~ c||~ go||~ java||
||# include-file[#include-file-note include file]||##gray|/* search path include system directories: /## _
#include _
_
##gray|/ search path also includes directory of source file */## _
#include “foo.h”|| || ||
||# add-system-dir[#add-system-dir-note add system directory]||$ gcc -I/opt/local/include foo.c|| || ||
||# def-macro[#def-macro-note define macro]||#define PI 3.14|| || ||
||# cmd-line-macro[#cmd-line-macro-note command line macro]||$ gcc -DPI=3.14 foo.c|| || ||
||# undef-macro[#undef-macro-note undefine macro]||#undef PI|| || ||
||macro with arguments||#define MIN(X, Y) ((X) < (Y) ? (X) : (Y))|| || ||
||stringify macro argument|| || || ||
||concatenate tokens|| || || ||
||conditional compilation||#if defined WIN32 _
@< >@win32_prinft(“%f\n”, x); _
#else _
@< >@printf(“%f\n”, x); _
#endif|| || ||
||macro operators||##gray|//The conditional of// #if //can contain integer literals and the following operators://## _
_
@@&&@@ @@||@@ ! _
@@==@@ != < > <= >= _
@@+@@ - * / % _
@@ << >> & | ^ ~ @@ _
_
##gray|//In addition, the// defined() //operator can be used to test whether a macro is defined.//## _
_
##gray|#ifdef FOO //is a shortcut for// #if defined(FOO)##|| || ||
||||||||~ # net-web[#net-web-note net and web]||
||~ ||~ c||~ go||~ java||
||# http-get[#http-get-note http get]|| ||import “io/ioutil” _
import “net/http” _
_
resp, err := http.Get(@@"http://www.google.com"@@) _
if err == nil { _
@< >@defer resp.Body.Close() _
@< >@body, err := ioutil.ReadAll(resp.Body) _
@< >@if err == nil { _
@< >@@< >@fmt.Println(string(body)) _
@< >@} _
}|| ||
||||||||~ # unit-tests[#unit-tests-note unit tests]||
||~ ||~ c||~ go||~ java||
||# unit-test-example[#unit-test-example-note example]||$ sudo apt-get install check _
_
$ cat > check_foo.c _
#include _
_
STARTTEST(testfoo) { _
@< >@fail_unless(0, “not true”); _
} _
END_TEST _
_
Suite * _
suite_foo(void) { _
@< >@Suite *ste = suite_create(“suite: foo”); _
@< >@TCase *tc = tcase_create(“case: foo”); _
_
@< >@tcaseaddtest(tc, test_foo); _
@< >@suiteaddtcase(ste, tc); _
_
@< >@return ste; _
} _
_
int _
main(void) { _
@< >@int number_failed; _
@< >@Suite *ste = suite_foo(); _
@< >@SRunner *sr = srunner_create(ste); _
_
@< >@srunnerrunall(sr, CK_NORMAL); _
@< >@numberfailed = srunnerntests_failed(sr); _
@< >@srunner_free(sr); _
_
@< >@return (number_failed); _
} _
_
$ gcc -o checkfoo checkfoo.c -lcheck _
_
$ ./check_foo _
Running suite(s): foo _
0%: Checks: 1, Failures: 1, Errors: 0 _
checkfoo.c:4:F:foo:testfoo:0: not equal||$ cat foo_test.go _
package foo _
_
import “testing” _
_
func TestFoo(t testing.T) { _
@< >@t.Errorf(“always fails”) _
} _
_
$ go test _
— FAIL: TestFoo (0.00s) _
@< >@foo_test.go:6: always fails _
FAIL _
exit status 1 _
FAIL _/Users/john/Lang/Go 0.007s|| ||
||||||||~ # debugging-profiling[#debugging-profiling-note debugging and profiling]||
||~ ||~ c||~ go||~ java||
||# check-syntax[#check-syntax-note check syntax]||$ gcc -fsyntax-only foo.c||$ go vet|| ||
||# stronger-warnings[#stronger-warnings-note flag for stronger warnings]||$ gcc -Wall foo.c|| || ||
||# suppress-warnings[#suppress-warnings-note suppress warnings]||$ gcc -w foo.c|| || ||
||# warnings-as-err[#warnings-as-err-note treat warnings as errors]||$ gcc -Werror foo.c|| || ||
||# lint[#lint-note lint]||$ sudo apt-get install splint _
$ splint foo.c|| || ||
||# src-cleanup[#src-cleanup-note source cleanup]|| ||$ go fmt|| ||
||# debugger[#debugger-note run debugger]||$ gcc -g -o foo foo.c _
$ gdb foo|| || ||
||# debugger-cmds[#debugger-cmds-note debugger commands] _
##gray|//help, list source, (re)load executable, next, step, set breakpoint, show breakpoints, delete breakpoint, continue, backtrace, up stack, down stack, print, run, quit//##||@@>@@ h _
@@>@@ l ##gray|[FIRSTLINENO, LASTLINENO]## _
@@>@@ file ##gray|PATH## _
@@>@@ n _
@@>@@ s _
@@>@@ b ##gray|[FILE:]LINENO## _
@@>@@ i _
@@>@@ d ##gray|NUM## _
@@>@@ c _
@@>@@ bt _
@@>@@ up _
@@>@@ do _
@@>@@ p ##gray|EXPR## _
@@>@@ r ##gray|[ARG1[, [ARG2 @@…@@]]## _
@@>@@ q|| || ||
||# benchmark[#benchmark-note benchmark code]||#include _
#include @< >@##gray|/ sysconf */## _
_
struct tms start, end; _
_
double tickspers = (double)sysconf(SCCLK_TCK); _
_
clockt startwall = times(&start); _
_
if (start_wall < 0) { _
@< >@fputs(“times failed”, stderr); _
@< >@return (1); _
} _
_
int i; _
for (i = 0; i < 1000 * 1000 * 1000; ++i) { _
@< >@##gray|/* empty loop */## _
} _
_
clockt endwall = times(&end); _
_
if (end_wall < 0) { _
@< >@fputs(“times failed”, stderr); _
@< >@return (1); _
} _
_
clockt wall = endwall - start_wall; _
clockt user = end.tmsutime - start.tms_utime; _
clockt system = end.tmsstime - start.tms_stime; _
_
printf(“wall: %f s\n”, wall / tickspers); _
printf(“user: %f s\n”, user / tickspers); _
printf(“system: %f s\n”, system / tickspers);||$ cat foo_test.go _
package foo _
_
import “testing” _
_
func BenchmarkFoo(b *testing.B) { _
@< >@for i := 0; i < 1000 * 1000 * 1000; i++ { _
@< >@} _
} _
_
$ go test -bench . _
goos: darwin _
goarch: amd64 _
BenchmarkFoo-8@< >@1000000000@< >@0.29 ns/op _
PASS _
ok _/Users/john/Lang/go 3.709s|| ||
||# profile[#profile-note profile code]||##gray|//does not work on Mac OS X//## _
$ gcc -pg -o foo foo.c _
$ ./foo _
$ gprof foo||$ cat foo_test.go _
package foo _
_
import “flag” _
import “fmt” _
import “testing” _
_
var cpuprofile = flag.String(“cpuprofile”, ““, ““) _
_
func Foo() int { _
@< >@for j := 0; j < 100; j++ { _
@< >@} _
@< >@return 1 _
} _
_
func BenchmarkFoo(b *testing.B) { _
@< >@for i := 0; i < 1000 * 1000 * 10; i++ { _
@< >@@< >@j := Foo() _
@< >@@< >@if j > 10 { _
@< >@@< >@@< >@fmt.Printf(“Unexpected”) _
@< >@@< >@} _
@< >@} _
} _
_
$ go tool pprof cpu.prof _
##gray|//type “top” to see profile//##|| ||
||# memory-tool[#memory-tool-note memory tool]||$ sudo apt-get install valgrind _
$ gcc -o foo foo.c _
$ valgrind foo|| || ||
||~ ||~ ##EFEFEF|@@____________________________________________________________@@##||~ ##EFEFEF|@@___________________________________________________________@@##||~ ##EFEFEF|@@______________________________________________________________@@##||
|||| || ||~ # fixed-length-arrays[#fixed-length-arrays-note fixed-length arrays]|| ||~ || || ||~ java|| ||# fixed-len-array-stack[#fixed-len-array-stack-note declare on stack]|| || ||##gray|//arrays must be allocated on heap//##|| ||# fixed-len-array-heap[#fixed-len-array-heap-note declare on heap]|| || ||int[] a = new int[10];|| ||# free-fixed-len-array-heap[#free-fixed-len-array-heap-note free heap]|| || ||##gray|//garbage collected//##|| ||# fixed-len-array-init-list[#fixed-len-array-init-list-note initialization list]|| || ||int[] a = {1,2,3};|| ||# fixed-len-array-size[#fixed-len-array-size-note size]|| || ||a.length|| ||# fixed-len-array-lookup[#fixed-len-array-lookup-note lookup] _ @< >@|| || ||a[0]|| ||# fixed-len-array-update[#fixed-len-array-update-note update] _ @< >@|| || || || ||# fixed-len-array-out-of-bounds[#fixed-len-array-out-of-bounds-note out-of-bounds]|| || ||ArrayIndexOutOfBoundsException|| ||# copy-fixed-len-array[#copy-fixed-len-array-note copy]|| || || || ||# fixed-len-array-as-func-arg[#fixed-len-array-as-func-arg-note as function argument]|| || || || ||# iterate-over-fixed-len-array[#iterate-over-fixed-len-array-note iterate]|| || ||for (String name : names) {|| ||# sort-fixed-len-array[#sort-fixed-len-array-note sort]|| || || ||
|||| || ||~ # resizable-arrays[#resizable-arrays-note resizable arrays]|| ||~ || || ||~ java|| ||# decl-resizable-array[#decl-resizable-array-note declare]|| || ||java.util.Vector vec = new java.util.Vector();|| ||# resizable-array-init-list[#resizable-array-init-list-note initialization list]|| || || || ||# resizable-array-capacity[#resizable-array-capacity-note capacity] _ ##gray|//get, increase//##|| || || || ||# resizable-array-empty-test[#resizable-array-empty-test-note empty test] _ ##gray|//and clear//##|| || || || ||# resizable-array-elem-index[#resizable-array-elem-index-note element index]|| || || || ||# concat-resizable-array[#concat-resizable-array-note concatenate]|| || || || ||# replicate-resizable-array-elem[#replicate-resizable-array-elem-note replicate element]|| || || || ||# resizable-array-as-func-arg[#resizable-array-as-func-arg-note array as function argument]|| || || || ||# indexed-array-iteration[#indexed-array-iteration-note iterate over elements and indices]|| || || || ||# reverse-array[#reverse-array-note reverse]|| || || || ||# dedupe-array[#dedupe-array-note dedupe]|| || || || ||# membership[#membership-note membership]|| || || ||
|||| || ||~ # dictionaries[#dictionaries-note dictionaries]|| ||~ || || ||~ java|| ||# dict-ctor[#dict-ctor-note constructor]|| || ||java.util.TreeMap m = new java.util.TreeMap();||
|||| || ||~ # functions[#functions-note functions]|| ||~ || || ||~ java|| ||# decl-func[#decl-func-note declare]|| || || || ||# call-func[#call-func-note call] _ @< >@|| || || || ||# def-static-class-method[#def-static-class-method-note define static class method]|| || || || ||# invoke-static-class-method[#invoke-static-class-method-note invoke static class method]|| || || || ||# default-arg[#default-arg-note default argument]|| || ||##gray|//use method overloading//##|| ||# pass-by-ref[#pass-by-ref-note pass by reference]|| || ||##gray|//objects and arrays are always passed by reference//##|| ||# recursive-func[#recursive-func-note recursive function]|| || || || ||# anon-func-literal[#anon-func-literal-note anonymous function]|| || || || ||# overload-op[#overload-op-note overload operator]|| || ||##gray|//none//##|| |||| || ||~ # execution-control[#execution-control-note execution control]|| ||~ || || ||~ java|| ||# break-nested-loops[#break-nested-loops-note break out of nested loops]|| || || || |||| || ||~ # exceptions[#exceptions-note exceptions]||
||~ || || ||~ java|| ||# base-exc[#base-exc-note base exception]|| || ||##gray|//Any type which implements the interface// java.lang.Throwable //can be thrown. _ _ Exceptions thrown by the language and the standard libraries derive from// java.lang.Errror //or// java.lang.Exception.##|| ||# predefined-exc[#predefined-exc-note predefined exceptions]|| || ||##gray|//java.lang.Throwable//## _ @< >@java.lang.Error _ @< >@java.lang.Exception _ @< >@@< >@java.lang.IOException _ @< >@@< >@java.lang.RuntimeException _ @< >@@< >@@< >@java.lang.ArithmeticException _ @< >@@< >@@< >@java.lang.IllegalArgumentException _ @< >@@< >@@< >@java.lang.IndexOutOfBoundsException _ @< >@@< >@@< >@java.lang.NullPointerException|| ||# raise-exc[#raise-exc-note raise exception]|| || ||throw new Exception(“failed”);|| ||# handle-exc[#handle-exc-note handle exception]|| || ||try { _ @< >@throw new Exception(“failed”); _ } _ catch (Exception e) { _ @< >@System.out.println(e.getMessage()); _ }|| ||# def-exc[#def-exc-note define exception]|| || || || ||# re-raise-exc[#re-raise-exc-note re-raise exception]|| || || || ||# catch-all-handler[#catch-all-handler-note catch-all handler]|| || || || ||# multiple-handlers[#multiple-handlers-note multiple handlers]|| || || || ||# uncaught-exc[#uncaught-exc-note uncaught exception behavior]|| || || || ||# error-msg[#error-msg-note error message]|| || || || ||# errno[#errno-note system call errno]|| || || || ||# finally-clause[#finally-clause-note finally clause]|| || ||try { _ @< >@##gray|//risky code//## _ } finally { _ @< >@##gray|//perform cleanup//## _ }|| ||# exc-specification[#exc-specification-note exception specification]|| || ||##gray|//yes//##||
|||| || ||~ # file-handles[#file-handles-note file handles]|| ||~ || || ||~ java|| ||[#read-file read from file]|| || ||import java.io.BufferedReader; _ import java.io.FileReader; _ _ BufferedReader in = new BufferedReader(new FileReader(“/etc/passwd”)); _ String line; _ _ while ((line = in.readLine()) != null) { _ @< >@##gray|@@//@@ process line## _ }|| ||[#write-file write to file]|| || ||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();||
|||| || ||~ # files[#files-note files]|| ||~ || || ||~ java|| ||# readable-writable-executable[#readable-writable-executable is file readable, writable, executable]|| || ||import java.io.File; _ _ File f = new File(“/etc/hosts”); _ _ f.canRead() _ f.canWrite() _ f.canExecute()||
|||| || ||~ # directories[#directories-note directories]|| ||~ || || ||~ java|| ||# iterate-dir[#dir-iterate-note iterate over directory by file]|| || ||import java.io.File; _ _ File dir = new File(“/etc”); _ _ ##gray|@@//@@ iterate over names:## _ for (String name: dir.list()) { _ @< >@System.out.println(name); _ } _ _ ##gray|@@//@@ iterate over file objects:## _ for (File f: dir.listFiles()) { _ @< >@System.out.println(f.getName()); _ }||
|||| || ||~ # processes-environment[#processes-environment-note processes and environment]|| ||~ || || ||~ java|| ||[#main signature of main]|| || ||public class //Foo// { _ @< >@public static void main(String[] args) {|| ||[#first-argument first argument] _ @< >@|| || ||##gray|//first command line argument//##|| ||[#environment-variable environment variable]|| || ||String home = System.getenv(“HOME”);|| ||[#iterate-environment-variable iterate through environment variables]|| || ||import java.util.Map; _ Map env = System.getenv(); _ for (String name : env.keySet()) { _ @< >@String value = env.get(name)); _ }||
|||| || ||~ # libraries-namespaces[#libraries-namespaces-note libraries and namespaces]|| ||~ || || ||~ java|| ||# std-lib-name[#std-lib-name-note standard library name]|| || ||##gray|//Java API//##|| ||[#declare-namespace declare namespace]|| || ||package foo.bar; _ public class Baz { _ @< >@public static final int ANSWER = 42; _ }|| ||[#namespaces-per-file multiple namespaces per file]|| || ||##gray|//no//##|| ||[#namespace-directory-mapping namespaces map to directories]|| || ||##gray|//yes//##|| ||[#import-namespace import namespace]|| || ||import foo.bar.*; _ System.out.println(Baz.ANSWER);|| ||[#import-part-namespace import part of namespace]|| || ||##gray|//none//##|| ||[#import-symbol import symbol]|| || ||import foo.bar.Baz; _ System.out.println(Baz.ANSWER);|| ||[#import-static-symbol import static symbol]|| || ||import static foo.bar.Baz.ANSWER; _ System.out.println(ANSWER);|| ||[#import-position import position] _ @< >@|| || ||##gray|//after package and before type definitions//##|| ||[#not-imported-symbol using a symbol that hasn’t been imported]|| || ||System.out.println(foo.bar.Baz.ANSWER);|| ||# app-env[#app-env-note application environment]|| || || || ||# multiple-installations[#multiple-installations-note multiple installations]|| || ||##gray|//set// JAVAHOME //environment variable to directory containing a// bin //subdirectory with// java, javac, //and other command line tools. Put// $JAVAHOME/bin //at front of search path.//##||
|||| || ||~ # user-defined-types[#user-defined-types-note user-defined types]|| ||~ || || ||~ java|| ||[#struct-definition struct definition]|| || ||public class MedalCount { _ @< >@public String country; _ @< >@public int gold; _ @< >@public int silver; _ @< >@public int bronze; _ }|| ||[#struct-declaration struct declaration]|| || ||MedalCount spain = new MedalCount();|| ||[#struct-initialization struct initialization]|| || ||##gray|//no object literal syntax; define a constructor//##|| ||[#struct-member-assignment struct member assignment]|| || ||spain.country = “Spain”; _ spain.gold = 3; _ spain.silver = 7; _ spain.bronze = 4;|| ||[#struct-member-access struct member access]|| || ||int spain_total = spain.gold + spain.silver + spain.bronze;|| |||| || ||~ # generic-types[#generic-types-note generic types]|| ||~ || || ||~ java|| ||[#define-generic define generic type]|| || ||public class Foo { _ @< >@public A a; _ @< >@public Foo(A a) { _ @< >@@< >@this.a = a; _ @< >@} _ }|| ||[#instantiate-generic instantiate generic type]|| || ||Foo f = new Foo(“foo”);|| ||[#generic-function generic function]|| || || || ||[#generic-array generic array]|| || ||##gray|//not permitted. Use// Object //as the element type for the array or use an// ArrayList.##|| ||[#value-parameter value parameter]|| || || || ||[#template-parameter template parameter]|| || || || ||[#template-specialization template specialization]|| || || || ||[#multiple-type-parameters multiple type parameters]|| || || || ||[#generic-type-parameters generic type parameters]|| || || || ||[#template-parameters template parameters]|| || || || ||variadic template|| || || ||
|||| || ||~ # objects[#objects-note objects]|| ||~ || || ||~ java|| ||# str-equal[#str-equal-note semantics of ==]|| || ||##gray|//object identity comparison//##|| ||[#define-class define class]|| || ||public class Rational { _ @< >@public int num; _ @< >@public int denom; _ @< >@public Rational add(Rational o) throws Exception { _ @< >@@< >@return new Rational(this.numo.denom + o.numthis.denom,this.denomo.denom); _ @< >@} _ @< >@public static Rational max(Rational a, Rational b) { _ @< >@@< >@return (a.numb.denom > a.num*b.denom) ? a : b; _ @< >@} _ }|| ||[#class-definition-location class definition location]|| || ||##gray|//top level, class block, or function block for anonymous classes//##|| ||[#constructor constructor]|| || ||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; _ @< >@} _ }|| ||[#create-object create object]|| || ||Rational r = new Rational(7,3);|| ||[#destructor destructor]|| || ||protected void finalize() throws Throwable { _ @< >@super.finalize(); _ }|| ||[#destroy-object destroy object] _ @< >@|| || ||##gray|//none//##|| ||[#define-method define method]|| || ||public int height() { _ @< >@return (Math.abs(this.num) > this.denom) ? Math.abs(this.num) : this.denom; _ }|| ||[#invoke-method invoke method]|| || ||r.height();|| ||[#define-class-method define class method]|| || ||##gray|//declare static in class definition//##|| ||[#invoke-class-method invoke class method]|| || || || ||[#receiver name of receiver]|| || ||this|| ||[#access-control access control]|| || ||##gray|//access keywords required for methods and members://## _ public class Foo { _ @< >@private int privateInt; _ @< >@protected int protectedInt; _ @< >@public int publicInt; _ }|| ||[#anonymous-class anonymous class]|| || ||(new Object() { public void hello() { System.out.println(“hello!”); } }).hello();||
|||| || ||~ # inheritance-polymorphism[#inheritance-polymorphism-note inheritance and polymorphism]|| ||~ || || ||~ java|| ||[#dynamic-dispatch dynamic dispatch]|| || ||##gray|//dispatch dynamic by default//##|| ||[#static-dispatch static dispatch]|| || ||##gray|//declare as final, private, or static (i.e. make it a class method)//##|| ||[#subclass subclass]|| || ||public class RInteger extends Rational { _ @< >@public RInteger(int n) throws Throwable { _ @< >@@< >@super(n, 1); _ @< >@} _ }|| ||[#superclass-constructor invoking superclass constructor]|| || ||super(n, 1);|| ||[#underivable-class mark class underivable or method unoverrideable]|| || ||final|| ||[#root-class root class] _ @< >@|| || ||java.lang.Object|| ||[#root-class-methods root class methods]|| || ||clone() _ equals() _ finalize() _ getClass() _ hashCode() _ toString()||
|||| || ||~ # reflection[#reflection-note reflection]|| ||~ || || ||~ java|| ||[#type-class get type class of object]|| || || o = new Object(); _ Class c = o.getClass();|| ||[#get-type-class-string get type class from string]|| || ||Class c = Class.forName(“java.io.File”);|| ||[#get-type-class-identifier get type class from type identifier]|| || || || ||[#class-name class name] _ @< >@|| || ||String name = c.getName();|| ||[#get-methods get methods]|| || ||import java.lang.reflect.; _ Method[] m = c.getMethods();|| ||[#has-method 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; _ @< >@} _ }|| ||[#invoke-method-object 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);|| |||| || ||~ # net-web[#net-web-note net and web]|| ||~ || || ||~ java|| ||get local hostname, dns lookup, reverse dns lookup|| || || || ||http get|| || || || ||http post|| || || || ||absolute url|| || || || ||parse url|| || || || ||# url-encode[#url-encode-note 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”);|| ||base64 encode/decode|| || || ||
# version-note ++ [#version Version]
# version-used-note ++ [#version-used version used]
The compiler version used for this cheatsheat.
# show-version-note ++ [#show-version show version]
How to get the compiler version.
# implicit-prologue-note ++ [#implicit-prologue implicit prologue]
Code which the examples in this sheet assume to have been executed.
c:
A selection of commonly used symbols and macros from the standard C library and the headers in which they are defined according to POSIX:
||~ [http://pubs.opengroup.org/onlinepubs/9699919799/functions/errno.html errno.h]||~ [http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/stdlib.h.html stdlib.h]||~ [http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/stdio.h.html stdio.h]||~ [http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/string.h.html string.h]||~ [http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/time.h.html time.h]||~ [http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/wchar.h.html wchar.h]|| ||errno _ _ ENOENT _ ENOMEM _ EACCES _ EINVAL _ EPIPE||abs _ drand48 _ exit _ free _ getenv _ lrand48 _ malloc _ mkdtemp _ putenv _ qsort _ realpath _ srand _ strtod _ strtol _ system _ unsetenv||fclose _ feof _ fflush _ fgets _ fopen _ fprintf _ fputs _ getc _ getline _ printf _ putc _ remove _ rename _ scanf _ _ BUFSIZ _ EOF _ NULL||strcat _ strchr _ strcmp _ strcpy _ strdup _ strerror _ strncat _ strncmp _ strncpy _ strndup _ strrchr _ strstr _ strtok||time _ time_t||swprintf _ wcscmp _ wcsdup _ wcslen _ wprintf||
# grammar-invocation-note + [#grammar-invocation Grammar and Invocation]
# hello-world-note ++ [#hello-world hello world]
How to write, compile, and run a “Hello, World!” program.
# file-suffixes-note ++ [#file-suffixes file suffixes]
The suffixes used for source files, header files, and compiled object files.
# stmt-terminator-note ++ [#stmt-terminator statement terminator]
How statements are terminated.
# block-delimiters-note ++ [#block-delimiters block delimiters]
How a block of statements is delimited.
# eol-comment-note ++ [#eol-comment end-of-line comment]
The syntax for a comment which is terminated by the end of the line.
c:
The {{//}} style comment first appeared in the C99 standard.
# multiple-line-comment-note ++ [#multiple-line-comment multiple line comment]
The syntax for a comment which can span multiple lines.
{{/* */}} style comments cannot be nested in C or Go.
# variables-expressions-note + [#variables-expressions Variables and Expressions]
# local-var-note ++ [#local-var variable]
How to declare a variable.
# free-heap-note ++ [#free-heap free heap]
How to free memory allocated on the heap.
# global-var-note ++ [#global-var global variable]
How to declare a global variable.
# uninitialized-var-note ++ [#uninitialized-var uninitialized variable]
What happens when reading from an uninitialized variable.
# compile-time-const-note ++ [#compile-time-const compile time constant]
How to define a constant.
go:
Multiple constants can be declared in this manner:
code const ( Pi = 3.14 E = 2.718 ) /code
# immutable-var-note ++ [#immutable-var immutable variable]
How to declare a variable which cannot change after initialization.
# assignment-note ++ [#assignment assignment]
The syntax for assigning a value to a variable.
# parallel-assignment-note ++ [#parallel-assignment parallel assignment]
The syntax for parallel assignment.
# swap-note ++ [#swap swap]
How to swap the values in two variables.
# compound-assignment-note ++ [#compound-assignment compound assignment]
The compound assignment operators.
# incr-decr-note ++ [#incr-decr increment and decrement]
The increment and decrement operators.
# null-note ++ [#null null]
The null literal and where the null value can be used.
c:
A typical definition:
code #define NULL (void *)0 /code
# null-test-note ++ [#null-test null test]
How to test whether a value is null.
# conditional-expr-note ++ [#conditional-expr conditional expression]
The syntax for a conditional expression.
# arithmetic-logic-note + [#arithmetic-logic Arithmetic and Logic]
# boolean-type-note ++ [#boolean-type boolean type]
c:
The following definitions are common:
code typedef int BOOL; #define TRUE 1 #define FALSE 0 /code
# true-false-note ++ [#true-false true and false]
Literals for the boolean values true and false.
c:
The following definitions are common:
code typedef int BOOL; #define TRUE 1 #define FALSE 0 /code
# falsehoods-note ++ [#falsehoods falsehoods]
Values which evaluate as false in the conditional expression of an {{if}} statement.
# logical-op-note ++ [#logical-op 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.
# relational-op-note ++ [#relational-op relational operators]
Binary operators which return boolean values.
# int-type-note ++ [#int-type integer type]
Signed integer types.
c:
Whether //char// is a signed or unsigned type depends on the implementation.
# unsigned-type-note ++ [#unsigned-type unsigned type]
Unsigned integer types.
c:
Whether //char// is a signed or unsigned type depends on the implmentation.
# float-type-note ++ [#float-type float type]
Floating point types.
# arith-op-note ++ [#arith-op arithmetic operators]
The arithmetic binary operators.
# int-div-note ++ [#int-div integer division]
How to find the quotient of two integers.
# int-div-zero-note ++ [#int-div-zero integer division by zero]
The result of attempting to divide an integer by zero.
c:
The behavior for division by zero is system dependent; the behavior described is common on Unix.
# float-div-note ++ [#float-div float division]
How to perform float division on integers.
# float-div-zero-note ++ [#float-div-zero float division by zero]
The result of attempting to divide a float by zero.
# power-note ++ [#power power]
How to perform exponentiation.
# sqrt-note ++ [#sqrt sqrt]
The square root function.
# sqrt-negative-one-note ++ [#sqrt-negative-one sqrt -1]
The result of attempting to find the square root of a negative nubmer.
# transcendental-func-note ++ [#transcendental-func transcendental functions]
The exponential function; logarithm functions; trigonometric and inverse trigonometric functions.
# transcendental-const-note ++ [#transcendental-const transcendental constants]
Constants for {{π}} and {{e}}.
# float-truncation-note ++ [#float-truncation float 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.
# absolute-val-note ++ [#absolute-val absolute value]
The absolute value of a numeric.
# complex-type-note ++ [#complex-type complex type]
Complex floating point types.
# complex-construction-note ++ [#complex-construction complex construction]
How to create a complex number.
c:
The C11 standard introduced macros for constructing complex numbers which work correctly when the arguments are inf, nan, or +nan:
code double complex CMPLX(double x, double y) float complex CMPLXF(float x, float y) long double complex CMPLXL(long double x, long double y) /code
# complex-decomposition-note ++ [#complex-decomposition complex decomposition]
How to decompose a complex number into its real and imaginary parts; how to get the argument and absolute value of a complex number; how to get its complex conjugate.
# random-num-note ++ [#random-num random number]
How to generate a random integer from a uniform distribution; how to generate a random float from a uniform distribution.
# random-seed-note ++ [#random-seed random seed]
How to set the random seed.
c:
There are at least three random number generators defined in {{stdlib.h}}. Each has its own function for setting the random seed:
code srand(17); /* used by rand() */
srandom(17); /* used by random() */
srand48(17); /* used by drand48() and lrand48() */ /code
# bit-op-note ++ [#bit-op bit operators]
The bit operations: right shift, left shift, and, or, exclusive or, and not.
go:
Note that ^ is bit-not and not exclusive-or like in C.
# binary-octal-hex-note ++ [#binary-octal-hex binary, octal, and hex literals]
# strings-note + [#strings Strings]
# str-type-note ++ [#str-type string type]
The type for a string.
c:
The C11 standard introduces {{char16t}} and {{char32t}}, but no literal syntax or functions which take them as arguments.
# str-literal-note ++ [#str-literal string literal]
The syntax for a string literal.
go:
The backquote literal is also called the raw string literal. It has no escape sequences; it cannot contain a backquote character.
# newline-in-str-literal-note ++ [#newline-in-str-literal newline in string literal]
Can newlines be included in string literals?
c:
The compiler will convert the following three string literals to the single literal {{"foobarbaz”}}.
code char *metavars = “foo” “bar” “baz”; /code
# str-literal-esc-note ++ [#str-literal-esc string escapes]
Escape sequences in string literals.
# compare-str-note ++ [#compare-str compare strings]
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.
# str-to-num-note ++ [#str-to-num string to number]
c:
//strtoimax//, //strtol//, //strtoll//, //strtoumax//, //strtoul//, and //strtoull// take three arguments:
code intmax_t strtoimax(const char *str, char **endp, int base); /code
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:
code double strtod(const char *str, char **endp); /code
# num-to-str-note ++ [#num-to-str number to string]
# split-note ++ [#split split]
# str-join-note ++ [#str-join join]
# str-concat-note ++ [#str-concat concatenate]
# str-replicate-note ++ [#str-replicate replicate]
# extract-substr-note ++ [#extract-substr extract substring]
# index-substr-note ++ [#index-substr index of substring]
# fmt-str-note ++ [#fmt-str format string]
# translate-case-note ++ [#translate-case translate case]
# trim-note ++ [#trim trim]
# pad-note ++ [#pad pad]
# str-len-note ++ [#str-len length]
# char-type-note ++ [#char-type character type]
The type for a character.
# char-literal-note ++ [#char-literal character literal]
# char-lookup-note ++ [#char-lookup character lookup]
# char-index-note ++ [#char-index character index]
# char-tests-note ++ [#char-tests character tests]
# chr-ord-note ++ [#chr-ord chr and ord]
# regexes-note + [#regexes Regular Expressions]
# regex-metachar-note ++ [#regex-metachar metacharacters]
The list of regular expression metacharacters.
A regular expression that does not contain any metacharacters matches itself as a string.
# char-class-abbrev-note ++ [#char-class-abbrev character class abbrevations]
Abbreviations for character classes.
c:
[http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/regex.h.html#tag_13_38 regex.h (POSIX 2008)]
We describe the {{regex}} library which is mandated by POSIX.
The PCRE library is available or easily installed on most systems and provides Perl style regular expressions. In particular PCRE has these character class abbreviations: {{\d \D \h \H \s \S \v \V \w \W}}.
To install PCRE on Ubuntu and read the documentation:
code $ sudo apt-get install pcre
$ man pcre /code
To include the PCRE definitions in a C file:
# regex-anchors-note ++ [#regex-anchors anchors]
Metacharacters for matching locations in the string which aren’t single characters or substrings.
# regex-test-note ++ [#regex-test match test]
How to test whether a string matches a regular expression.
# case-insensitive-regex-note ++ [#case-insensitive-regex case insensitive match test]
How to test whether a string matches a regular expression in a case insensitive manner.
# regex-modifiers-note ++ [#regex-modifiers modifers]
Modifers which can be used to customize the behvaior of a regular expression.
go:
The meaning of the modifiers:
||i||case insensitive match|| ||m||^ and $ match begin and end of line in addition to begin and end of string|| ||s||l. matches \n|| ||U||make (foo), (foo)+ non-greedy and (foo)?, (foo)+? greedy||
# subst-note ++ [#subst substitution]
How to replace the part of a string matching a regular expression.
# group-capture-note ++ [#group-capture group capture]
How to use a regular expression to parse a string.
# dates-time-note + [#dates-time Dates and Time]
# unix-epoch-type-note ++ [#unix-epoch-type unix epoch type]
# broken-down-datetime-type-note ++ [#broken-down-datetime-type broken-down datetime type]
# current-unix-epoch-note ++ [#current-unix-epoch current unix epoch]
# current-datetime-note ++ [#current-datetime current datetime]
# broken-down-datetime-to-unix-epoch-note ++ [#broken-down-datetime-to-unix-epoch broken-down datetime to unix epoch]
# unix-epoch-to-broken-down-datetime-note ++ [#unix-epoch-to-broken-down-datetime unix epoch to broken-down datetime]
# fmt-datetime-note ++ [#fmt-datetime format datetime]
# parse-datetime-note ++ [#parse-datetime parse datetime]
# date-subtraction-note ++ [#date-subtraction date subtraction]
# add-duration-note ++ [#add-duration add duration]
# date-parts-note ++ [#date-parts date parts]
# time-parts-note ++ [#time-parts time parts]
# build-datetime-note ++ [#build-datetime build broken-down datetime]
# local-tmz-determination-note ++ [#local-tmz-determination local time zone determination]
# tmz-info-note ++ [#tmz-info time zone info]
# daylight-savings-test-note ++ [#daylight-savings-test daylight savings test]
# microseconds-note ++ [#microseconds microseconds]
# fixed-length-arrays-note + [#fixed-length-arrays Fixed-Length Arrays]
# declare-array-note ++ [#declare-array declare]
How to declare an array variable.
# allocate-array-on-stack-note ++ [#allocate-array-on-stack allocate on stack]
How to allocate an array on the stack.
# allocate-array-on-heap-note ++ [#allocate-array-on-heap allocate on heap]
How to allocate an array on the heap.
# free-array-on-heap-note ++ [#free-array-on-heap free heap]
How to free an array that was allocated on the heap.
# array-literal-note ++ [#array-literal literal]
Syntax for an array literal.
# array-size-note ++ [#array-size size]
How many elements are stored in an array.
# array-lookup-note ++ [#array-lookup lookup]
How to get an element by index.
c:
Arrays can be manipulated with pointer syntax. The following sets //x// and //y// to the same value:
code int a[] = {3,7,4,8,5,9,6,10}; int x = a[4]; int y = *(a+4); /code
# array-update-note ++ [#array-update update]
How to set or change the element stored at an index.
# array-out-of-bounds-note ++ [#array-out-of-bounds out-of-bounds behavior]
What happens when an attempt is made to access an element at an invalid index.
# array-element-index-note ++ [#array-element-index element index]
# slice-array-note ++ [#slice-array slice]
# slice-array-to-end-note ++ [#slice-array-to-end slice to end]
# array-back-note ++ [#array-back manipulate back]
# array-front-note ++ [#array-front manipulate front]
# concatenate-array-note ++ [#concatenate-array concatenate]
# copy-array-note ++ [#copy-array copy]
# iterate-over-array-note ++ [#iterate-over-array iterate over elements]
How to iterate over the elements of an array.
c:
C arrays do not store their size; if needed the information can be stored in a separate variable. Another option is to use a special value to mark the end of the array:
code char *a[] = { “Bob”, “Ned”, “Amy”, NULL }; int i; for (i=0; a[i]; i++) { printf(“%s\n”, a[i]); } /code
# reverse-array-note ++ [#reverse-array reverse]
How to reverse the elements of an array.
# sort-array-note ++ [#sort-array sort]
How to sort the elements of an array.
# resizable-arrays-note + [#resizable-arrays Resizable Arrays]
# declare-resizable-array-note ++ [#declare-resizable-array declare]
How to declare a resizable array variable.
# resizable-array-literal-note ++ [#resizable-array-literal literal]
Syntax for a resizable array literal.
# resizable-array-size-note ++ [#resizable-array-size size]
How many elements are stored in a resizable array.
# resizable-array-lookup-note ++ [#resizable-array-lookup lookup]
How to get an element by index.
c:
Arrays can be manipulated with pointer syntax. The following sets //x// and //y// to the same value:
code int a[] = {3,7,4,8,5,9,6,10}; int x = a[4]; int y = *(a+4); /code
# resizable-array-update-note ++ [#resizable-array-update update]
How to set or change the element stored at an index.
# resizable-to-fixed-note ++ [#resizable-to-fixed resizable to fixed array]
How to convert a resizable array to a fixed array.
# fixed-to-resizable-note ++ [#fixed-to-resizable fixed to resizable array]
How to convert a fixed array to a resizable array.
# resizable-array-out-of-bounds-note ++ [#resizable-array-out-of-bounds out-of-bounds behavior]
What happens when an attempt is made to access an element at an invalid index.
# resizable-array-element-index-note ++ [#resizable-array-element-index element index]
How to get the index of an element in a resizable array.
# slice-resizable-array-note ++ [#slice-resizable-array slice]
How to slice a resizable array.
# slice-resizable-array-to-end-note ++ [#slice-resizable-array-to-end slice to end]
How to slice a resizable array to the end.
# resizable-array-back-note ++ [#resizable-array-back manipulate back]
How to add and remove elements from the back of a resizable array.
# resizable-array-front-note ++ [#resizable-array-front manipulate front]
How to add and remove elements from the front of a resizable array.
# concatenate-resizable-array-note ++ [#concatenate-resizable-array concatenate]
How to concatenate resizable arrays.
# copy-resizable-array-note ++ [#copy-resizable-array copy]
How to copy a resizable array.
# iterate-over-resizable-array-note ++ [#iterate-over-resizable-array iterate over elements]
How to iterate over the elements of a resizable array.
c:
C arrays do not store their size; if needed the information can be stored in a separate variable. Another option is to use a special value to mark the end of the array:
code char *a[] = { “Bob”, “Ned”, “Amy”, NULL }; int i; for (i=0; a[i]; i++) { printf(“%s\n”, a[i]); } /code
# iterate-indices-elem-note ++ [#iterate-indices-elem iterate over indices and elements]
How to iterate over the indices and elements of a resizable array.
# reverse-resizable-array-note ++ [#reverse-resizable-array reverse]
How to reverse the elements of a resizable array.
# sort-resizable-array-note ++ [#sort-resizable-array sort]
How to sort the elements of a resizable array.
# dictionaries-note + [#dictionaries Dictionaries]
# declare-dict-note ++ [#declare-dict declare]
# dict-literal-note ++ [#dict-literal literal]
# dict-size-note ++ [#dict-size size]
# dict-lookup-note ++ [#dict-lookup lookup]
# dict-update-note ++ [#dict-update update]
# dict-missing-key-note ++ [#dict-missing-key missing key behavior]
# dict-is-key-present-note ++ [#dict-is-key-present is key present]
# dict-delete-note ++ [#dict-delete delete]
# dict-iter-note ++ [#dict-iter iterate]
# functions-note + [#functions Functions]
# def-func-note ++ [#def-func define function]
How to define a function.
# invoke-func-note ++ [#invoke-func invoke function]
How to invoke a function.
# forward-decl-func-note ++ [#forward-decl-func forward declaration of function]
How to declare a function without defining it.
# overload-func-note ++ [#overload-func overload function]
How to define multiple functions with the same name. The functions differ in either the number or type of arguments.
# nest-func-note ++ [#nest-func nest function]
How to define a function inside another function.
# default-val-param-note ++ [#default-val-param default value for parameter]
# variable-num-arg-note ++ [#variable-num-arg 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.
code 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 *retval);
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; } /code
An example of use:
code string *s = concat(“Hello”, “, “, “World”, “!”, NULL); /code
# named-param-note ++ [#named-param named parameters]
# pass-by-val-note ++ [#pass-by-val pass by value]
# pass-by-addr-note ++ [#pass-by-addr pass by address]
# retval-note ++ [#retval return value]
How the return value for a function is determined.
# no-retval-note ++ [#no-retval no return value]
How to define a function with no return value.
swift:
The return value can be explicitly declared as {{Void}}:
code func print_err(err: String) -> Void { println(err) } /code
# multiple-retval-note ++ [#multiple-retval multiple return values]
How to return multiple values.
# named-retval-note ++ [#named-retval named return values]
How to return values by assigning values to variables.
# exec-on-return-note ++ [#exec-on-return execute on return]
How to register a function to be executed on return of the calling function.
go:
Arguments of the on-return function are evaluated at the time the function is registered and not when the caller returns.
Multiple on-return functions are evaluated in LIFO order.
# anonymous-func-literal-note ++ [#anonymous-func-literal anonymous function literal]
# invoke-anonymous-func-note ++ [#invoke-anonymous-func invoke anonymous function]
# func-private-state-note ++ [#func-private-state function with private state]
# closure-note ++ [#closure closure]
# func-as-val-note ++ [#func-as-val function as value]
# execution-control-note + [#execution-control Execution Control]
# if-note ++ [#if if]
The if statement.
An if statement is a series of blocks, each guarded by a conditional expression. The first conditional expression statement which evaluates to true determines the block which executes. An optional else block executes if none of the of the conditional expressions are true.
# switch-note ++ [#switch switch]
The switch statement.
The switch statement has a switch expression which is evaluated against one or more case values. The first case value which is equal to the switch expression determines the block which executes. An optional default block executes if none of the case values are equal.
Note that in some languages, execution “falls through” to the next block in a switch unless prevented by a break statement.
go:
Case values can be expressions.
The switch statement can lack a switch expression, in which case the first case value which evaluates to true determines the block to execute. Such a switch statement differs little from an if statement, but note that {{fallthrough}} cannot be used in an if statement.
It is possible to switch on type of an expression, in which case the case values are types:
code switch x.(type) { case nil: printString(“x is nil”) case int: printString(“x is int”) case float64: printFloat64(“x is float64”) default: printString(“unknown type”) } /code
# while-note ++ [#while while]
A while loop is a conditional expression and a block. The conditional expression is evaluated before each execution of the block. The block is executed iteratively as long as the conditional expression is true.
c:
C has a do-while statement. The block is always executed at least once. The conditional expression is evaluated before the second and subsequent iterations to determine if the block is executed again.
code int i = 0;
do { print(“%d\n”, ++i); } while (i < 10); /code
If the body of a while loop consists of a single statement the curly braces are optional:
code int i = 0; while (i<10) printf(“%d\n”, ++i); /code
# for-note ++ [#for for]
A for loop has four parts: the //initialization// which executes at the outset, the //condition// which is evaluated before each iteration, the //body// which is executed if the condition is true, and the //afterthought// which is executed after each execution of the body.
# for-local-scope-note ++ [#for-local-scope for with local scope]
Whether variables declared in the initialization are local to the body.
# infinite-loop-note ++ [#infinite-loop infinite loop]
The syntax for an infinite loop.
# break-note ++ [#break break]
A break statement is used to exit a loop.
# break-from-nested-loops-note ++ [#break-from-nested-loops break from nested loops]
How to break out of nested loops.
# continue-note ++ [#continue continue]
A continue statement is used to terminate the current iteration of a loop.
# single-stmt-branch-loop-note ++ [#single-stmt-branch-loop single statement branches and loops]
# dangling-else-note ++ [#dangling-else dangling else]
# goto-note ++ [#goto goto]
# longjmp-note ++ [#longjmp longjmp]
# concurrency-note + [#concurrency Concurrency]
# file-handles-note + [#file-handles File Handles]
# std-file-handles-note ++ [#std-file-handles standard file handles]
The file handles for standard input, standard output, and standard error.
c:
POSIX systems provide processes with the ability to open multiple files and manipulate them with via integers called file descriptors. Normally the integers 0, 1, and 2 refer to standard input, standard output, and standard error. The header defines the macros STDINFILENO, STDOUTFILENO, and STDERR_FILENO for these file descriptors.
System calls take file descriptors as arguments, but the C standard library provides an alternate set functions for buffered I/O. The standard library functions use {{FILE}} structs to identify streams and open files.
# read-line-stdin-note ++ [#read-line-stdin read line from stdin]
How to read a line from standard input.
# write-line-stdout-note ++ [#write-line-stdout write line to stdout]
How to write a line to standard output.
# printf-note ++ [#printf write formatted string to stdout]
How to print a formatted string to standard out.
c:
The [http://linux.die.net/man/3/printf printf man page] describes the notation used in C style format strings.
# open-file-note ++ [#open-file open file for reading]
How to open a file for reading.
# open-file-write-note ++ [#open-file-write open file for writing]
How to open a file for reading.
# open-file-append-note ++ [#open-file-append open file for appending]
How to open a file for appending.
# close-file-note ++ [#close-file close file]
How to close a file handle.
# close-file-implicitly-note ++ [#close-file-implicitly close file implicitly]
# io-err-note ++ [#io-err i/o errors]
# read-line-note ++ [#read-line read line]
# file-line-iterate-note ++ [#file-line-iterate iterate over file by line]
# read-file-array-note ++ [#read-file-array read file into array of strings]
# read-file-str-note ++ [#read-file-str read file into string]
# write-str-note ++ [#write-str write string]
# write-line-note ++ [#write-line write line]
# flush-note ++ [#flush flush file handle]
# eof-test-note ++ [#eof-test end-of-file test]
# seek-note ++ [#seek get and set file handle position]
# tmp-file-note ++ [#tmp-file open unused file]
How to open a file with a previously unused file name.
c:
The function {{mkstemps}} can be used to create a new file with a fixed suffix: “/tmp/fooXXXXXXsuffix”.
# files-note + [#files Files]
# file-test-note ++ [#file-test file test, regular file test]
Does the file exist; is the file a regular file.
# file-size-note ++ [#file-size file size]
The size of the file in bytes.
# readable-writable-executable-note ++ [#readable-writable-executable is file readable, writable, executable]
Can the process read, write, or executable the file?
c:
{{access}} returns 0 if the process has the permission, and -1 if it doesn’t or some other error occurred.
{{access}} uses the real user id to determine permission even though the kernel uses the effective user id.
# chmod-note ++ [#chmod set file permissions]
# file-cp-rm-mv-note ++ [#file-cp-rm-mv copy file, remove file, rename file]
# symlink-note ++ [#symlink create symlink, symlink test, readlink]
# unused-file-name-note ++ [#unused-file-name generate unused file name]
# file-fmt-note + [#file-fmt File Formats]
# directories-note + [#directories Directories]
# working-dir-note ++ [#working-dir working directory]
# build-pathname-note ++ [#build-pathname build pathname]
# dirname-basename-note ++ [#dirname-basename dirname and basename]
# absolute-pathname-note ++ [#absolute-pathname absolute pathname]
# dir-iterate-note ++ [#dir-iterate iterate over directory by file]
# glob-note ++ [#glob glob paths]
# mkdir-note ++ [#mkdir make directory]
# recursive-cp-note ++ [#recursive-cp recursive copy]
# rmdir-note ++ [#rmdir remove empty directory]
# rm-rf-note ++ [#rm-rf remove directory and contents]
# dir-test-note ++ [#dir-test directory test]
# unused-dir-note ++ [#unused-dir generate unused directory]
# system-tmp-dir-note ++ [#system-tmp-dir system temporary file directory]
# processes-environment-note + [#processes-environment Processes and Environment]
# first-argument ++ 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.
# env-var-note ++ [#env-var environment variable]
# env-var-iter-note ++ [#env-var-iter iterate over environment variables]
# exit-note ++ [#exit exit]
How to set the exit status and cause the process to exit.
c:
On POSIX systems zero indicates success and other values indicate failure.
On Linux and Mac OS X the value returned to the parent is {{exit_arg & 0377}}. If the process exited because of a signal, the kernel sets the exit status to 128 plus the signal number. The signals are numbered starting from 1, leaving exit status values from 1 to 127 and perhaps 128 available for other failure conditions.
The C standard library defines the values EXITSUCCESS and EXITFAILURE as an aid for writing code which is portable to systems which do not use 0 to indicate success.
# signal-handler-note ++ [#signal-handler set signal handler]
How to set a signal handler on a POSIX system.
A quirk about {{signal}} is that some systems (e.g. Solaris) do not leave the signal handler registered after handling a signal. Mac OS X and Linux do leave the signal handler registered.
For portability, one can used {{sigaction}} instead of {{signal}}.
Before writing a signal handler, review the list of permitted functions that you can call from the signal handler. The list is available in {{man 2 sigaction}} on Mac OS X and {{man 7 signal}} on Linux.
code $ man 2 sigaction
$ man 7 signal /code
- re-entrant functions
- sigaction
# send-signal-note ++ [#send-signal send signal]
# option-parsing-note + [#option-parsing Option Parsing]
# libraries-namespaces-note + [#libraries-namespaces Libraries and Namespaces]
# load-lib-note ++ [#load-lib load library]
How to load a library.
c:
Loading a library is a two part process.
Library declarations are made available by including headers in the client code.
Linking is performed by listing the library objects with the client object containing the {{main}} function on the command line when invoked the linker.
Alternatively, library objects can be collected into archive files using the {{ar}} command. These files have a {{.a}} suffix. The -l (lowercase L) option is used to include an archive when linking.
go:
Multiple libraries can be loaded by listing them one after another:
code import “fmt” import “math/rand” /code
Alternatively a single import statement can be used:
code import ( “fmt” “math/rand” ) /code
# load-lib-subdir-note ++ [#load-lib-subdir load library in subdirectory]
How to load a library in a subdirectory of the load path.
# lib-path-note ++ [#lib-path library path]
How to the library path is specified.
# declare-namespace-note ++ [#declare-namespace declare namespace]
How to declare the namespace of a source file.
# alias-namespace-note ++ [#alias-namespace alias namespace]
How to import a namespace under an alias.
This can be used to provide an abbreviated name for a namespace.
It also allows a client to use two different libraries which declare the same namespace.
# unqualified-import-note ++ [#unqualified-import unqualified import of namespace]
How to import all the identifiers in a library so that the client can refer to them without the namespace prefix.
# objects-note + [#objects Objects]
# def-class-note ++ [#def-class define class]
# create-object-note ++ [#create-object create object]
# def-method-note ++ [#def-method define method]
# invoke-method-note ++ [#invoke-method invoke method]
# subclass-note ++ [#subclass subclass]
# user-defined-types-note + [#user-defined-types User-Defined Types]
# typedef-note ++ [#typedef 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:
code typedef int int32_t; /code
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.
# enum-note ++ [#enum 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.
code enum { a=0, b, c=0, d }; /code
A //typedef// can be used to make the //enum// keyword unnecessary in variable declarations:
code typedef enum { mon, tue, wed, thu, fri, sat, sun } dayofweek; dayofweek d = tue; /code
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:
code enum dayofweek { mon, tue, wed, thu, fri, sat, sun }; dayofweek d = 10;
typedef enum { mon, tue, wed, thu, fri, sat, sun } dayofweek2; dayofweek2 d2 = 10; /code
# struct-definition ++ 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 [http://en.wikipedia.org/wiki/Uniform_access_principle uniform access principle].
# struct-declaration ++ struct declaration
# struct-initialization ++ 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 assignment
# struct-member-access ++ 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:
code struct medal_count { char* country; int gold; int silver; int bronze; }
struct medalcount spain = { “Spain”, 3, 7 4 }; struct medalcount winner = &spain; printf(“The winner is %s with %d gold medals”, (winner).country, (*winner).gold); /code
//ptr->mem// is a shortcut for //(*ptr).mem//:
code printf(“The winner (%s) earned %d silver medals”, winner->country, winner->silver); /code
# cpp-macros-note + [#cpp-macros C Preprocessor Macros]
# net-web-note + [#net-web Net and Web]
# http-get-note ++ [#http-get http get]
How to make an HTTP GET request.
# unit-tests-note + [#unit-tests Unit Tests]
# unit-test-example-note ++ [#unit-test-example example]
# debugging-profiling-note + [#debugging-profiling Debugging and Profiling]
# c + [#top C]
[http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf ANSI C Standard (pdf)] 1999 [http://www.gnu.org/software/libc/manual/html_mono/libc.html GNU C Library]
code FREQUENTLY USED GCC and CLANG OPTIONS
-o name of output file
TYPE OF BUILD
-E stop after preprocessor; do not compile -S stop after compilation; do not assemble -c stop after assembly; do not link
PREPROCESSOR
-I add directory to list of directories containing header files -D FOO define macro FOO as 1 -D FOO=VAL define macro FOO as VAL -U FOO undefine macro FOO -M output make dependency info
LINKER
-lfoo search library foo for symbols when liking -L add directory to search path used by -l
WARNINGS
-w no warnings -Werror make warnings errors -Wall enable all warnings
DEBUGGING, PROFILING, and OPTIMIZATION
-g make object debuggable -pg generate executable which produces output for gprof -O1 -O2 -O2 spend progressively more time in compilation optimizing code
MAC SPECIFIC
-F add a framework directory (used in place of -I, -l, -L) /code
# go + [#top Go]
[http://golang.org/doc/go_spec.html Language Specification] [http://golang.org/pkg/ Package Reference]
# java + [#top Java]
[http://java.sun.com/javase/6/docs/api/ Java 1.6 API] [https://jdk7.java.net/ JDK 7 Project] [http://java.sun.com/docs/books/jvms/second_edition/html/VMSpecTOC.doc.html JVM Specification 2nd Ed] [http://java.sun.com/docs/books/jls/ The Java Language Specification 3rd Ed]
A Java program is created from source code via an explicit compilation step using {{javac}}. The executable is then launched using the virtual machine {{java}}. Both {{javac}} and {{java}} use the Java runtime jar {{rt.jar}}, which contains the Java standard libraries.
code $ ls -l $(which javac) -rwxrwxr-x 1 root wheel 99296 Oct 8 2013 /Library/JVM/jdk7.0/Contents/Home/bin/javac
$ ls -l $(which java) -rwxrwxr-x 1 root wheel 99216 Oct 8 2013 /Library/JVM/jdk7.0/Contents/Home/bin/java
$ ls -l $JAVA_HOME/jre/lib/rt.jar -rw-rw-r– 1 root wheel 64181940 Oct 8 2013 /Library/JVM/jdk7.0/Contents/Home/jre/lib/rt.jar
$ cat Main.java public class Main { public static void main(String[] argv) throws Throwable { System.out.println(“Hello, World!”); } }
$ javac Main.java
$ ls -l Main.class -rw-r–r– 1 hpglot staff 463 Dec 27 06:12 Main.class
$ java Main Hello, World! /code
Using {{dtruss}} on Mac OS X to verify that {{javac}} and {{java}} use {{rt.jar}}:
code $ sudo dtruss javac Main.java 2>&1 | grep -E ‘^open’ | grep rt.jar open(“/Library/JVM/jdk7.0/Contents/Home/jre/lib/rt.jar\0”, 0x0, 0x0) = 4 0
$ sudo dtruss java Main 2>&1 | grep -E ‘^open’ | grep rt.jar open(“/Library/JVM/jdk7.0/Contents/Home/jre/lib/rt.jar\0”, 0x0, 0x0) = 4 0 /code