aBlaze aBlaze - 4 months ago 23
C Question

(C) Function which impersonates a block of code in main

I'm trying to explain this satisfactorily, but when I call a function I want it to virtually insert itself into the main function's code, so I can save typing it out multiple times, however it directly affects variables defined in main. What's the best way to achieve this?

EDIT: I should probably make it clear I also want it to take a single argument.


Sounds like you need a preprocessor macro. These aren't real functions, but blocks of code the the preprocessor replaces before compiling the code. E.g., consider a simple macro to increment a number:

#include <stdio.h>

#define INC(x) x++

int main() {
    int a = 1;
    printf("%d\n", a);
    return 0;

The text INC(x) will be replaced with x++, so running this program will print out 3 (1 after two increments).

You could read more about macros in the Documentation (beta) Topic.