System Programming Languages: C, Go

a side-by-side reference sheet; see also C++, Objective C, Java, C#

primitive types | arithmetic and logic | strings | dates and time | arrays | structs | dictionaries | functions | execution control | files | directories | processes and environment | libraries and namespaces | reflection | contact | edit

c (1972) go (2009)
hello word $ cat hello.c
#include <stdio.h>
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")
}
$ 6g hello.go
$ 6l hello.6
$ ./6.out
Hello, World!
version used
 
gcc 4.2.1 6g version release.r56
version
 
$ gcc —version $ 6g -V
libraries used
 
C standard library
source, header, object file suffix .c .h .o
null
 
NULL
printf
 
printf("count: %d\n", 7);
case and underscores in names A_MACRO_NAME
a_method_name()
a_variable_name
coalesce
 
char *s1 = s2 || "was null";
primitive types
c go
declare primitive type on stack int i;
int j = 3;
allocate primitive type on heap #include <stdlib.h>
int *ip = malloc(sizeof(int));
free primitive type on heap #include <stdlib.h>
free(ip);
value of uninitialized primitive types stack variables and heap variables allocated with malloc have indeterminate values. Global and static variables and heap variables allocated with calloc are zero-initialized.
boolean types
 
none
signed integer types signed char 1+ byte
short int 2+ bytes
int 2+ bytes
long int 4+ bytes
long long int 4+ bytes
unsigned integer types unsigned char: 8+
unsigned short int 2 bytes+
unsigned int 2 bytes+
unsigned long int 4+ bytes
unsigned long long int 4+ bytes
floating point and decimal types float
double
long double
typedef typedef int customer_id;
customer_id cid = 3;
enum enum day_of_week { mon, tue, wed, thu, fri, sat, sun };
enum day_of_week d = tue;
arithmetic and logic
c go
true and false
 
none
falsehoods
 
0 0.0 NULL
logical operators && || !
relational operators == != < > <= >=
operators
 
+ - * / %
power #include <math.h>
pow(2.0,3.0);
absolute value #include <stdlib.h>
int i = -7;
abs(i);
#include <math.h>
float x = -7.77;
fabs(x)
transcendental functions defined in <math.h>:
sqrt exp log log2 log10 sin cos tan asin acos atan atan2
arithmetic truncation #include <math.h>
 
double d = 3.77;
 
long trunc = (long)d;
long rnd = round(d);
long flr = floorl(d);
long cl = ceill(d);
closure of integers under division integers
division by zero process sent a SIGFPE signal
random integer #include <stdlib.h>
int i = rand();
bit operators << >> & | ^ ~
strings
c go
string type
 
char *
literal
 
"hello"
allocate string #include <string.h>
char *s = strdup("hello");
length
 
strlen("hello")
comparison strcmp("hello", "world")
semantics of == object identity comparison
numeric conversion strtoimax strtol strtoll
strtoumax strtoul strtoull
strtof strtod strtold
split
join
 
concatenate char *s1 = "hello";
char *s2 = " world";
char *s3 = (char *)calloc(strlen(s1) + strlen(s2) + 1,sizeof(char));
strcpy(s3,s1);
strcat(s3,s2);
substring char target[3];
char *source = "hello";
strncpy(target, source+2, 2);
index const char *s = "hello";
const char *p = strstr("hello", "ll");
p ? p - s : -1;
sprintf char buf[100];
snprintf(buf, 100, "%s: %d", "Spain", 7);
uppercase char *s = strdup("hello");
int i;
for (i=0; i<strlen(s); i++) {
s[i] = toupper(s[i]);
}
lowercase char *s = strdup("HELLO");
int i;
for (i=0; i<strlen(s); i++) {
s[i] = tolower(s[i]);
}
trim
pad on right char buf[100];
snprintf(buf, 100, "%-10s", "hello");
regex match #include <regex.h>
regex_t re;
if (regcomp(&re, "ll", REG_EXTENDED)) {
  handle error
}
int is_match = (regexec(&re, "hello", (size_t) 0, NULL, 0) == 0);
regfree(&re);
regex substitute
dates and time
c go
arrays
c go
allocate array on stack int a[10];
allocate array on heap #include <stdlib.h>
int *a = calloc(10, sizeof(int));
free array on heap #include <stdlib.h>
free(a);
array literal int a[] = {1,2,3};
array access
 
a[0]
length
 
none
array out-of-bounds result undefined, possible SIGSEGV
array iteration int a[10];
for (i=0; i<10; i++ ) {
  do something with a[i]
}
structs
c go
struct definition struct medal_count {
  const char* country;
  int gold;
  int silver;
  int bronze;
};
struct declaration struct medal_count spain;
struct initialization struct medal_count spain = { "Spain", 3, 7, 4};
struct medal_count france = {
  .gold = 8,
  .silver = 7,
  .bronze = 9,
  .country = "France"
};
struct member assignment spain.country = "Spain";
spain.gold = 3;
spain.silver = 7;
spain.bronze = 4;
struct member access int spain_total = spain.gold + spain.silver + spain.bronze;
union definition union perl_scalar {
char *string;
long integer;
double number;
void *reference;
}
union declaration union perl_scalar x;
union access
 
x.integer = 7;
dictionaries
c go
map declaration
map access
map remove element
map iterate
functions
c go
pass by value void use_integer(int i) {
  function body
}
int i = 7;
use_integer(i);
pass by address void use_iptr(int *i) {
  function body
}
int i = 7;
use_iptr(&i);
pass by reference none
default argument value none
named parameters none
function overloading no
variable number of arguments char* concat(int cnt, …) {
  int i, len;
  va_list ap;
  char *retval, *arg;
  va_start(ap, cnt);
  for (i=0, len = 0; i < cnt; i++) {
    len += strlen(va_arg(ap, char*));
  }
  va_end(ap);
  retval = calloc(len+1,sizeof(char));
  va_start(ap, cnt);
  for (i=0,len=0; i < cnt; i++) {
    arg = va_arg(ap, char*);
    strcpy(retval+len, arg);
    len += strlen(arg);
  }
  va_end(ap);
  return retval;
}
char *s = concat(4, "Hello", ", ", "World", "!");
passing functions
anonymous function
execution control
c go
for int i, n;
for (i=1,n=1; i<=10; i++) {
  n *= i;
}
if if (i>0) {
  signum = 1;
} else if (i==0) {
  signum = 0;
} else {
  signum = -1;
}
while int i = 0;
while (i<10) {

  i++;
}
switch switch(i) {
case 0:
  0;
  break;
case 1:
  1;
  break;
default:
  -1;
  break;
}
files
c go
read from file #include <stdio.h>
char buf[2000];
FILE *f;
if (!(f = fopen("/etc/passwd", "r")) {
  handle error
};
while (fgets(buf, 2000, f) {
  process buf
}
if (ferror(f)) {
  handle error
}
if (fclose(f)) {
  handle error
}
write to file #include <stdio.h>
FILE *f;
if (!(f= fopen("/tmp/test1","w")) {
  handle error
};
int i;
for (i=0; i<10; i++) {
  fprintf(f, "%d\n", i);
}
if (ferror(f)) {
  handle error
}
if (fclose(f)) {
  handle error
}
directories
c go
processes and environment
c go
signature of main int main(int argc, char **argv) {
first argument
 
pathname of executable
environment variable #include <stdlib.h>
char *home = getenv("HOME");
setenv("EDITOR", "emacs", 1);
unsetenv("EDITOR");
iterate thru environment variables
libraries and namespaces
c go
declare namespace
multiple namespaces per file
namespaces map to directories
import namespace
import part of namespace
import symbol
import static symbol
import position
 
using a symbol that hasn't been imported
reflection
c go
________________________________________________________________________________________ ________________________________________________________________________________________

General Footnotes

hello world

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

version used

The compiler version used for this cheatsheat.

version

How to get the compiler version.

libraries used

The libraries used for this reference sheet.

C

C Standard Library
GNU C Library

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

source, header, and object file suffix

null

C

A typical definition:

#define NULL (void *)0

printf

How to print a formatted string to standard out.

case and underscores in names

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

coalesce

The equivalent of the COALESCE function from SQL.

C:

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

Primitive Type Footnotes

declare primitive type on stack

How to declare a primitive type on the stack.

allocate primitive type on heap

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

free primitive type on heap

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

value of uninitialized types

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

boolean types

C

The following definitions are common:

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

signed integer types

C

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

unsigned integer types

C

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

floating point and decimal types

C#

typedef

C

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

typedef int int32_t;

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

enum

C

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

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

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

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

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

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

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

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

Arithmetic and Logic Footnotes

true and false

Literals for the boolean values true and false.

C

The following definitions are common:

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

falsehoods

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

logical operators

The logical operators.

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

relational operators

Binary operators which return boolean values.

operators

The arithmetic binary operators.

power

How to perform exponentiation.

absolute value

The absolute value of a numeric quantity.

transcendental functions

The square root function and the transcendental functions.

arithmetic truncation

Functions for converting a float to a nearby integer value.

C:

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

closure of integers under division

division by zero

C:

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

random integer

bit operators

String Footnotes

string type

string literal

allocate string

string length

string comparison

C

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

to C string

numeric conversion

C

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

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

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

strtof, strtod, and strtold take three arguments:

double
strtod(const char *str, char **endp);

split

join

concatenate

substring

index

sprintf

uppercase

lowercase

trim

pad

regex match

C

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

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

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

regex substitute

Date and Time Footnotes

Array Footnotes

allocate array on stack

How to allocate an array on the stack.

allocate array on heap

How to allocate an array on the heap.

free array on heap

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

array literal

array element access

C

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

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

array out-of-bounds result

array iteration

C

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

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

Struct Footnotes

struct definition

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

struct declaration

struct initialization

C

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

struct member assignment

struct member access

C

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

struct medal_count {
char* country;
int gold;
int silver;
int bronze;
}

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

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

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

union definition

union access

Dictionary Footnotes

map declaration

C:

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

map access

map size

map remove

map element not found result

map iterator

Function Footnotes

pass by value

pass by address

pass by reference

default argument value

named parameters

function overloading

variable number of arguments

C

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

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

An example of use:

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

passing functions

anonymous function

operator overloading

Execution Control Footnotes

for

if

The curly braces surrounding an if or else clause are optional if the clause contains a single statement. The resulting dangling else ambiguity is resolved by setting the value of c to 2 in the following code:

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

while

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

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

switch

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

File Footnotes

read from file

C

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

write to file

Directory Footnotes

Processes and Environment Footnotes

signature of main

first argument

C

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

environment variable

iterate thru environment variables

Library and Namespace Footnotes

Reflection Footnotes

C

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

Go

Language Specification
Package Reference

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