locked
Accessing variable RRS feed

  • Question

  • Hello ...

    Suppose i have a function, where i dont give the variable name in the function argument (only data type) as shown below..

    void fun(int)
    {
                 // Want to print the argument passed to the function
       
    }

    How do we access the argument passed to the variable ??? The above code compiles properly (after adding fun. call and main()).

     

    Thanks in advance... :)

    Wednesday, December 8, 2010 1:04 PM

Answers

All replies

  • Suppose i have a function, where i dont give the variable name in the function argument (only data type) as shown below..
     
    void fun(int)
    {
                 // Want to print the argument passed to the function
    }
     
    How do we access the argument passed to the variable ??? The above code compiles properly (after adding fun. call and main()).
    You can't. If you want to use the argument, you have to give it a name.
     
    Why are you asking this question?
     

    David Wilkinson | Visual C++ MVP
    • Proposed as answer by mr_jeff Wednesday, December 8, 2010 6:43 PM
    Wednesday, December 8, 2010 1:09 PM
  • To add to David's response, be aware that if you declare a function:

    void fun(int y)
    {...}

    it doesn't mean that the parameter passed to fun() must be named "y".

    int MyVariable = 10;
    fun(MyVariable);

    will work just fine.

    Wednesday, December 8, 2010 4:52 PM
  • Hello David,

    Thanks for the response.... but the idea behind the question is, if we can not access, then whats the point having the provision like this in the language... why its not treated as "at least warning" case ... ???

    or to put it in other words, when we may require this kind of functionality....

    Thursday, December 9, 2010 3:53 AM
  • >why its not treated as "at least warning" case ... ?

    Compile it as C rather than C++ and see what happens.

    - Wayne
    Thursday, December 9, 2010 4:48 AM
  • >when we may require this kind of functionality....

    Why does C++ allow unnamed function parameters?
    http://www.comeaucomputing.com/techtalk/#argwithnoname

    - Wayne
    • Marked as answer by NiteshKC Thursday, December 9, 2010 5:29 AM
    Thursday, December 9, 2010 4:58 AM
  • Thanks Wayne... it has good explanation.. :):)

    David:: Pl. have look @ the link in Wayne's post..

    Thursday, December 9, 2010 5:29 AM
  • Thanks Wayne... it has good explanation.. :):)
     
    David:: Pl. have look @ the link in Wayne's post..
    Your question was how can you use the parameter if it is not named, not why you would use an un-named parameter...
     
    One situation not mentioned in the link is with virtual functions, where one or more of the implementations does not need a particular parameter.
     

    David Wilkinson | Visual C++ MVP
    Thursday, December 9, 2010 12:53 PM