How to change the output of printf() in main()?

Here we will see how to change the output of the printf() function from main(). We will define a macro that will modify all printf() statements to use a different value than what is passed to it.

We will use the #define macro to accomplish this task. This macro will be defined inside a function, allowing us to control when the printf() behavior changes. By calling the function from main(), we can control exactly when printf() starts behaving differently.

Syntax

#define printf(format, value) printf(format, replacement_value);

Example

In this example, we define a macro inside a function that makes all printf() calls output 50 regardless of the actual variable value −

#include <stdio.h>

void changePrintf() {
    #define printf(x, y) printf(x, 50);
}

int main() {
    int x = 40;
    
    printf("Before calling changePrintf(): %d<br>", x);
    
    changePrintf();
    
    printf("After calling changePrintf(): %d<br>", x);
    
    x = 60;
    printf("Changed variable to 60: %d<br>", x);
    
    return 0;
}
Before calling changePrintf(): 40
After calling changePrintf(): 50
Changed variable to 60: 50

How It Works

The macro redefinition works at the preprocessing stage. When the preprocessor encounters the #define directive inside the function, it replaces all subsequent printf() calls with the modified version. The second parameter is always replaced with 50, regardless of the actual variable value passed.

Key Points

  • The #define macro works at compile time during preprocessing
  • Once the macro is defined, it affects all subsequent printf() calls in the same compilation unit
  • This technique demonstrates macro redefinition but should be used carefully in production code
  • The original printf() behavior before calling changePrintf() remains unchanged

Conclusion

Using #define macros inside functions allows us to control when printf() behavior changes. This demonstrates the power of C preprocessor macros to modify function behavior at compile time.

Updated on: 2026-03-15T10:31:45+05:30

391 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements