Stateful Policy Composition
Lesson 40 of 48 in Coddy's C for C# Developers course.
C# closures retain captured variables through managed objects. C stateful callbacks borrow an explicit context whose lifetime must cover the calls; the callback does not automatically keep it alive.
Pair a context pointer with a function pointer to pass stateful behavior. The context must remain alive during every invocation.
C# example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
class Program {
static void Main(){
int factor=3;Func<int,int> policy=n=>factor*n;Console.WriteLine(policy(4));
}
}
C# output:
12C example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
struct Policy {void *context;int (*apply)(void*,int);};
static int multiply(void *context,int n){return *(int*)context*n;}
int main(void) {
int factor=3;struct Policy p={&factor,multiply};printf("%d\n",p.apply(p.context,4));
return 0;
}
C output:
12Challenge
EasyPolicy stores context and apply(context,value). Implement price_with(policy,value) by invoking the supplied callback once with the same context. Input is factor and value. Driver also supplies an offset policy and checks invocation count, so hard-coded multiplication is insufficient.
Edit the unlocked source and header files. Keep the declared public API compatible with the visible locked main.c, which calls it directly. Do not add another main. All numeric task fixtures are small enough to avoid overflow unless the task explicitly checks a range. Print only the specified output; the driver supplies input parsing and output when shown.
Try it yourself
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
static int multiply(void *context,int n){return *(int*)context*n;}
typedef struct {int offset,calls;} Counter;
static int shifted(void *context,int n){Counter *p=context;p->calls++;return n+p->offset;}
int main(void){int factor,value;if(scanf("%d%d",&factor,&value)!=2)return 1;Counter c={7,0};if(price_with((Policy){&c,shifted},3)!=10 || c.calls!=1)return 3;printf("%d\n",price_with((Policy){&factor,multiply},value));return 0;}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in C for C# Developers
1Compile and Compute
Run C Across FilesPrinting and CommentsTypes and InitializationInteger Division and RangeFloating ArithmeticRecap: Receipt Total4Functions and Interfaces
Function Arguments Are ValuesHeaders and LinkageMultiple Results via PointersConst Views and MutationRecap: Price Breakdown2Decisions and Loops
Booleans and BranchesLogical OperatorsSwitch and Enumerated CasesLoop Bounds and ProgressRecap: Admission Rules5Pointers and Structs
Addresses and DereferencingPointer Steps and BoundariesRecords as Struct ValuesMutable Struct APIsRecap: Point Translation8Tagged Data and Composition
Enums and Tagged RecordsFunction Pointer CallbacksSorting with a ComparatorStateful Policy CompositionCleanup on Every PathRecap: Select a PolicyPractice on your own: Online C compiler