[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 443
  • Last Modified:

printf can not be a macro defined in terms of fprintf ?

Please explain following sentence from 'C' language book:

"Note, though, that unlike getchar and fgetc, printf can not be a macro defined in terms of fprintf, because macros can not have a variable number of arguments."

Please provide example of how there will be variable number of arguments if printf is a macro defined in terms of fprintf ?
0
naseeam
Asked:
naseeam
  • 2
  • 2
2 Solutions
 
SStoryCommented:
printf can have variable number of args.

printf("Good morning, %s, did you know that %d + %d = %d?",name,5,5,10);
printf("Good morning, %s",name);

Here printf has 4 args (5 including the string) in the first, and 1 or 2 in the second. It is saying you can't do this in the macro because it won't allow variable args..I think.
0
 
naseeamAuthor Commented:
Please provide example of printf being a macro defined in terms of fprintf.  Then, explain why it can't be done.
0
 
jkrCommented:
Well, you can create 'getchar()' as a macro from 'fgetc()' like

#define getchar fgetc(stdin)

Open in new window


The same or something similar is isn't possible because 'printf()' takes a variable number of 0 up to n arguments, which cannot be taken care of with a macro, since the latter always takes a defined number of arguments (with the notable exception of gcc, but that's a non-standard compiler extendion).
0
 
SStoryCommented:
#define dontwork fprintf(stdin,txt)

It won't work because fprintf can take tons of args based on the format string.  For every %d or %s etc in the string there must be a ,arg1,arg2...,argn

I don not know how much better anyone can explain this.  The above macro expects a single text string with no variables.  How many would you make?  You can not know.  Normally functions like that have an argv array of items or something and maybe the count argc...
0
 
naseeamAuthor Commented:
Great explanation with great examples.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now