Thread: Preprocessor trick for variable number of args

  1. #1
    Work in Progress..... Jaken Veina's Avatar
    Join Date
    Mar 2005
    Location
    Missouri. Go Imos Pizza!
    Posts
    256

    Preprocessor trick for variable number of args

    I know I've seen something like this before, but it's been a while and I can't get it to work. Does this ring a bell for anyone...

    Code:
    #include <stdio.h>
    
    #define DEBUG(t)  fprintf(debug_out, t)
    
    int main(void)
     {
      FILE* debug_out = fopen("debug.txt", "w");
    
      DEBUG("This is only a test...\n");
      DEBUG(("1 = %i\n", 1));
      DEBUG("This was only a test...\n");
    
      fclose(debug_out);
    
      return 0;
     }
    The theory is that if you encase printf's arguments in parentheses, the macro will take them as a single argument, and everything works fine...except I'm forgetting something, and the compiler simplifies
    Code:
    ("1 = %i\n", 1)
    to just
    Code:
    1
    Any thoughts? Thanks in advance.
    Code:
    void function(void)
     {
      function();
     }

  2. #2
    Registered User
    Join Date
    Aug 2008
    Location
    Belgrade, Serbia
    Posts
    163
    Look at this.
    Vanity of vanities, saith the Preacher, vanity of vanities; all is vanity.
    What profit hath a man of all his labour which he taketh under the sun?
    All the rivers run into the sea; yet the sea is not full; unto the place from whence the rivers come, thither they return again.
    For in much wisdom is much grief: and he that increaseth knowledge increaseth sorrow.

  3. #3
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    Quote Originally Posted by Jaken Veina View Post
    [CODE] DEBUG(("1 = %i\n", 1));
    You are assuming that the expression will be parsed, evaluated and passed as a single argument to the DEBUG macro which takes a const char * as its parameter.

  4. #4
    Work in Progress..... Jaken Veina's Avatar
    Join Date
    Mar 2005
    Location
    Missouri. Go Imos Pizza!
    Posts
    256
    It certainly would be more efficient to just use the compiler's built-in functionality for variable-argument-macros. Good thing I've got it.
    Code:
    void function(void)
     {
      function();
     }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. adding a number to a number
    By bigmac(rexdale) in forum C Programming
    Replies: 11
    Last Post: 10-24-2007, 12:56 PM
  2. Calculating next prime number
    By anilemon in forum C Programming
    Replies: 8
    Last Post: 04-17-2006, 10:38 AM
  3. Finding a number within a number
    By jeev2005 in forum C Programming
    Replies: 2
    Last Post: 01-10-2006, 08:57 PM
  4. Prime number program problem
    By Guti14 in forum C Programming
    Replies: 11
    Last Post: 08-06-2004, 04:25 AM
  5. parsing a number
    By juancardenas in forum C Programming
    Replies: 1
    Last Post: 02-19-2003, 01:10 PM