Skip to content
Related Articles

Related Articles

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

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 21 Jun, 2022
Improve Article
Save Article

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)

This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!