C, Go

a side-by-side reference sheet

grammar and invocation | variables and expressions | arithmetic and logic | strings | regexes | dates and time | fixed-length-arrays | resizable arrays | dictionaries | functions | execution control | concurrency | file handles | files | file formats | directories | processes and environment | option parsing | libraries and namespaces | objects | user-defined types | c preprocessor macros | net and web | unit tests | debugging and profiling

The compiler version used for this cheatsheat.

How to get the compiler version.

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:

errno.h stdlib.h stdio.h string.h time.h 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

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

The suffixes used for source files, header files, and compiled object files.

How statements are terminated.

How a block of statements is delimited.

The syntax for a comment which is terminated by the end of the line.

c:

The // style comment first appeared in the C99 standard.

The syntax for a comment which can span multiple lines.

/* */ style comments cannot be nested in C or Go.

How to declare a variable.

How to free memory allocated on the heap.

How to declare a global variable.

What happens when reading from an uninitialized variable.

How to define a constant.

go:

Multiple constants can be declared in this manner:

const ( Pi = 3.14 E = 2.718 )

How to declare a variable which cannot change after initialization.

The syntax for assigning a value to a variable.

The syntax for parallel assignment.

How to swap the values in two variables.

The compound assignment operators.

The increment and decrement operators.

The null literal and where the null value can be used.

c:

A typical definition:

#define NULL (void *)0

How to test whether a value is null.

The syntax for a conditional expression.

c:

The following definitions are common:

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

Literals for the boolean values true and false.

c:

The following definitions are common:

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

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

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.

Binary operators which return boolean values.

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 types.

The arithmetic binary operators.

How to find the quotient of two integers.

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.

How to perform float division on integers.

The result of attempting to divide a float by zero.

How to perform exponentiation.

The square root function.

The result of attempting to find the square root of a negative nubmer.

The exponential function; logarithm functions; trigonometric and inverse trigonometric functions.

Constants for π and e .

Functions for converting a float to a nearby integer value.

c:

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

The absolute value of a numeric.

Complex floating point types.

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:

double complex CMPLX(double x, double y) float complex CMPLXF(float x, float y) long double complex CMPLXL(long double x, long double y)

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.

How to generate a random integer from a uniform distribution; how to generate a random float from a uniform distribution.

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:

srand(17); /* used by rand() */ srandom(17); /* used by random() */ srand48(17); /* used by drand48() and lrand48() */

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.

The type for a string.

c:

The C11 standard introduces char16_t and char32_t , but no literal syntax or functions which take them as arguments.

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.

Can newlines be included in string literals?

c:

The compiler will convert the following three string literals to the single literal "foobarbaz" .

char *metavars = "foo" "bar" "baz";

Escape sequences in string literals.

c:

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

c:

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);

The type for a character.

The list of regular expression metacharacters.

A regular expression that does not contain any metacharacters matches itself as a string.

Abbreviations for character classes.

c:

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:

$ sudo apt-get install pcre $ man pcre

To include the PCRE definitions in a C file:

#include <pcre.h>

Metacharacters for matching locations in the string which aren't single characters or substrings.

How to test whether a string matches a regular expression.

How to test whether a string matches a regular expression in a case insensitive manner.

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

U make (foo)*, (foo)+ non-greedy and (foo)*?, (foo)+? greedy

How to replace the part of a string matching a regular expression.

How to use a regular expression to parse a string.

How to declare an array variable.

How to allocate an array on the stack.

How to allocate an array on the heap.

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

Syntax for an array literal.

How many elements are stored in an array.

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:

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

How to set or change the element stored at an index.

What happens when an attempt is made to access an element at an invalid index.

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:

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

", a[i]); }

How to reverse the elements of an array.

How to sort the elements of an array.

How to declare a resizable array variable.

Syntax for a resizable array literal.

How many elements are stored in a resizable array.

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:

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

How to set or change the element stored at an index.

How to convert a resizable array to a fixed array.

How to convert a fixed array to a resizable array.

What happens when an attempt is made to access an element at an invalid index.

How to get the index of an element in a resizable array.

How to slice a resizable array.

How to slice a resizable array to the end.

How to add and remove elements from the back of a resizable array.

How to add and remove elements from the front of a resizable array.

How to concatenate resizable arrays.

How to copy a resizable array.

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:

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

", a[i]); }

How to iterate over the indices and elements of a resizable array.

How to reverse the elements of a resizable array.

How to sort the elements of a resizable array.

How to define a function.

How to invoke a function.

How to declare a function without defining it.

How to define multiple functions with the same name. The functions differ in either the number or type of arguments.

How to define a function inside another function.

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 *retval); va_start(ap, first); strcpy(retval, first); len = strlen(first); while (1) { arg = va_arg(ap, char*); if (!arg) { break; } printf("copying %s

", arg); strcpy(retval+len, arg); len += strlen(arg); } va_end(ap); return retval; }

An example of use:

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

How the return value for a function is determined.

How to define a function with no return value.

swift:

The return value can be explicitly declared as Void :

func print_err(err: String) -> Void { println(err) }

How to return multiple values.

How to return values by assigning values to variables.

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.

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.

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:

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") }

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.

int i = 0; do { print("%d

", ++i); } while (i < 10);

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

", ++i);

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.

Whether variables declared in the initialization are local to the body.

The syntax for an infinite loop.

A break statement is used to exit a loop.

How to break out of nested loops.

A continue statement is used to terminate the current iteration of a loop.

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 <unistd.h> defines the macros STDIN_FILENO, STDOUT_FILENO, 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.

How to read a line from standard input.

How to write a line to standard output.

How to print a formatted string to standard out.

c:

The printf man page describes the notation used in C style format strings.

How to open a file for reading.

How to open a file for reading.

How to open a file for appending.

How to close a file handle.

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".

Does the file exist; is the file a regular file.

The size of the file in bytes.

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.

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.

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 EXIT_SUCCESS and EXIT_FAILURE as an aid for writing code which is portable to systems which do not use 0 to indicate success.

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.

$ man 2 sigaction $ man 7 signal

re-entrant functions

sigaction

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:

import "fmt" import "math/rand"

Alternatively a single import statement can be used:

import ( "fmt" "math/rand" )

How to load a library in a subdirectory of the load path.

How to the library path is specified.

How to declare the namespace of a source file.

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.

How to import all the identifiers in a library so that the client can refer to them without the namespace prefix.

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.

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;

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);

How to make an HTTP GET request.

ANSI C Standard (pdf) 1999

GNU C Library

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)

Language Specification

Package Reference