fredag 26. februar 2016

typedef, structs and function pointers

Just a quick reminder about structs and typedefs in C:

A named struct is created like this:

struct MyStruct{
  int anInt;

A custom type like this:

typedef int MyType;

The two syntaxes may be combined like this

typedef struct MyStruct{
  int anInt;
} MyType;

In use you can then either write

void myFunction(struct MyStruct someValue);


void myFunction(MyType someValue);

in the latter case omitting the struct keyword.

Function pointers

A variable containing a pointer to a function can be written like this:

returnType (*pointerName)(parameterType)

For example:

void (*myFunctionPointer)(int)

The pointer is then for example assigned like this:

myFunctionPointer = &someFunction;

Combined with typedef you can get:

typedef void (*myFunctionPointerType)(int)

and then use myFunctionPointer as a type:

myFunctionPointer aFunction = &someFunction;

Ingen kommentarer:

Legg inn en kommentar