Thread: Passing different types of arguments to a function as one parameter?

  1. #1
    Registered User
    Join Date
    Mar 2002
    Posts
    2

    Question Passing different types of arguments to a function as one parameter?

    Hi everyone I have a question: How can I make a function accept different types of arguments? For example, a square function that takes int, float, long and double that computes the square of the argument and is transparent to the data type of the argument:

    void square ( ??????? n) {
    printf ("%f", (float) n*n);
    }

    Is this doable? Thanks a lot!

  2. #2
    Registered User
    Join Date
    Aug 2001
    Location
    computers/ theatre, travelingstudentL>- Northern California NativeNorthern California3D&Tie-DyeStudent1>. Admirer of C Bangalore Net surfingTeacher >/ >0 nagpurteaching >1  >2
    Posts
    61
    In C++ it is done with function overloading.

    In C you can pass an additional parameter that declares the type of the other parameter. ie:

    void square(int type, void *value)
    switch(type)
    {
    case: 1 /* int */
    printf("%d", (int)*value * (int)*value);
    break:
    case: 2 /* float */
    printf("%f", (float)*value * (float)*value);
    ...

    If you look in the FAQ your will find an entry for variable argument lists, this is another method that can be used.

  3. #3
    Registered User
    Join Date
    Mar 2002
    Posts
    2
    Thank you!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 11-21-2008, 04:27 PM
  2. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  3. Passing arguments to another function
    By Wiretron in forum C Programming
    Replies: 2
    Last Post: 12-24-2006, 05:57 AM
  4. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM
  5. Passing arguments to function...
    By alvifarooq in forum C++ Programming
    Replies: 8
    Last Post: 09-24-2004, 12:50 PM