Open In App

How to Change the Output of printf() in main() in C?

Improve
Improve
Like Article
Like
Save
Share
Report

To change the output of printf() in main(), we can use Macro Arguments.

#define macro can be used for this task. This macro is defined inside the function. Although, #define can be used without declaring it in the function, in that case always the printf() will be changed. The function needs to be called first to change the output of printf() in main().

Consider the following program. Change the program so that the output of printf() is always 10. 

C




// C Program to demonstrate changing the output of printf()
// in main()
#include <stdio.h>
 
void fun()
{
    // Add something here so that the printf in main prints
    // 10
}
 
// Driver Code
int main()
{
    int i = 10;
    fun();
    i = 20;
    printf("%d", i);
    return 0;
}


It is not allowed to change main(). Only fun() can be changed. Now, consider the following program using Macro Arguments,

C




// C Program to demonstrate the use of macro arguments to
// change the output of printf()
#include <stdio.h>
 
void fun()
{
#define printf(x, y) printf(x, 10);
}
 
// Driver Code
int main()
{
    int i = 10;
    fun();
    i = 20;
    printf("%d", i);
    return 0;
}


Output

10

Time Complexity: O(1)

Auxiliary Space: O(1)

 



Last Updated : 21 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads