Skip to content

Instantly share code, notes, and snippets.

@alg0trader
Last active December 15, 2015 01:59
Show Gist options
  • Save alg0trader/5183694 to your computer and use it in GitHub Desktop.
Save alg0trader/5183694 to your computer and use it in GitHub Desktop.
Mimic of Object-Oriented Class in C language.
#include <stdio.h>
#include "interface.h"
static void print_hi(char *name)
{
printf("Hi %s\r\n", name);
}
static void print_bye(char *name)
{
printf("Bye %s\r\n", name);
}
static void inc_array(int *pArray, int len)
{
int i;
for(i = 0; i < len; i++)
pArray[i]++; // Increment each element by +1
}
// Define functions
const sMenu foo =
{
print_hi,
print_bye,
inc_array
};
#ifndef INTERFACE_H
#define INTERFACE_H
typedef struct
{
void (*print_hi)(char *name);
void (*print_bye)(char *name);
void (*inc_array)(int *pArray, int len);
} sMenu;
extern const sMenu foo;
#endif // INTERFACE_H
/*******************************************************************************
*
* Author: Austin Schaller
* Module: main.c
* Description: C Class Implementation
*
*******************************************************************************/
/*
* This program tests the ability for function pointers to behave in a manner
* similar to that of a class in C++. 'print_hi', 'print_bye', and inc_array
* are statically defined in static_test.c, but we are allowed to access them
* through 'sMenu'.
*/
#include <stdio.h>
#include "interface.h"
#define LEN_ARRAY 3 // Length of array
int main()
{
int i;
int A[LEN_ARRAY] = {0, 1, 2};
foo.print_hi("John Doe");
foo.print_bye("John Doe");
printf("\r\n--- Initial Array ---\r\n");
// Check contents before modifying array
for(i = 0; i < LEN_ARRAY; i++)
printf("A[%d]: %d\r\n", i, A[i]);
foo.inc_array(&A[0], LEN_ARRAY); // Increment each element by +1
printf("\r\n--- Modified Array ---\r\n");
// Check contents after modifying array
for(i = 0; i < LEN_ARRAY; i++)
printf("A[%d]: %d\r\n", i, A[i]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment