Skip to content
Related Articles

Related Articles

Improve Article

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

  • Difficulty Level : Medium
  • Last Updated : 29 May, 2017

Consider the following program. Change the program so that the output of printf is always 10. It is not allowed to change main(). Only fun() can be changed.




void fun()
{
    // Add something here so that the printf in main prints 10
}
  
int main()
{
    int i = 10;
    fun();
    i = 20;
    printf("%d", i);
    return 0;
}

We can use Macro Arguments to change the output of printf.




#include <stdio.h>
  
void fun()
{
   #define printf(x, y) printf(x, 10);
}
  
int main()
{
    int i = 10;
    fun();
    i = 20;
    printf("%d", i);
    return 0;
}

Output:

10

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

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :