Thread: call by reference question

  1. #1
    Registered User
    Join Date
    Aug 2004

    call by reference question

    Id like to pass 1 variable from main to funk and receive more than one back to printf on main.
    Well I guess I can give an array from main then use the elements array(0...n] in funk and print it out in main.
    am I rigth?

    BUT can I do like this....
    which bothers me causeI get lots of errors.
    void funk(); /*prototype*/
       funk( e.g   &var1) /*passing one variable to funk  */
    void funk ( *var1, *var2, *var3) /*returning moe than one to main*/

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Oregon, USA
    No, funk() must receive the same number of args that main() passes to it. You'll need to declare each var in main() and pass each one to funk().
    #include <stdio.h>
    void funk(int *n1, int *n2, int *n3)
      *n1 = 1;
      *n2 = 2;
      *n3 = 3;
    int main(void)
      int n1, n2, n3;
      funk(&n1, &n2, &n3);
      return 0;
    Something like that.
    Last edited by itsme86; 09-09-2004 at 12:28 PM.
    If you understand what you're doing, you're not learning anything.

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    >void funk();
    >void funk ( *var1, *var2, *var3)
    Mixing old style declarations and new style definitions is a bad idea. When your prototype has an empty parameter list, you are not saying that it takes no arguments. You are saying that it takes an unknown number and type of arguments, which is most certainly not what you intended I imagine.

    And I would recommend against trying to pass a different number of arguments than you tell the function to expect. If you really want to a variable number of arguments, write a function with a variable length argument list:
    #include <stdio.h>
    #include <stdarg.h>
    void funk ( int narg, ... );
    int main ( void )
      int var1, var2, var3;
      funk ( 1, &var1 );
      funk ( 2, &var2, &var3 );
      printf ( "%d\n%d\n%d\n", var1, var2, var3 );
      return 0;
    void funk ( int narg, ... )
      va_list args;
      int i = 0;
      va_start ( args, narg );
      while ( --narg >= 0 )
        *va_arg ( args, int * ) = i++;
      va_end ( args );
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  2. call by value, reference, name...
    By magic101 in forum C Programming
    Replies: 11
    Last Post: 05-06-2008, 03:23 AM
  3. Call by reference help!
    By yigster in forum C Programming
    Replies: 1
    Last Post: 05-02-2008, 09:19 AM
  4. Call by reference...
    By Mak in forum C Programming
    Replies: 4
    Last Post: 11-13-2003, 03:53 PM
  5. function call question?
    By correlcj in forum C++ Programming
    Replies: 7
    Last Post: 10-11-2002, 05:33 PM