Where ampersand “&” can be put when passing argument by reference?

前端 未结 4 1813
抹茶落季
抹茶落季 2020-12-10 11:58

In the examples that I saw the arguments were passed by reference in the following way:

void AddOne(int &y)

In the code that I have I s

相关标签:
4条回答
  • 2020-12-10 12:10

    It is a matter of style. Both are correct and valid.

    However it seems Bjarne Stroustrup prefers putting the & and * beside the type name, emphasising the type of the variable:

    int* i;   // i is a pointer to an int 
    int& j;   // j is a reference to an int
    
    

    See here for the pointers: https://www.stroustrup.com/bs_faq2.html#whitespace

    See examples in "Programming Principles and Practices using C++" book and here for references: https://stackoverflow.blog/2019/10/11/c-creator-bjarne-stroustrup-answers-our-top-five-c-questions/

    0 讨论(0)
  • 2020-12-10 12:23

    There is no differences between

    void AddOne(int &y);
    

    and

    void AddOne(int& y);
    

    and even

    void AddOne(int&y);
    

    in C++, as the whitespaces between actual tokens are discarded.

    0 讨论(0)
  • 2020-12-10 12:24

    It's the same for the language, just different code conventions

    0 讨论(0)
  • 2020-12-10 12:27

    Both are exactly the same. No difference at all.

    All that matters is that & should be between the type and the variable name. Spaces don't matter.

    So

    void AddOne(int&  y);
    void AddOne(int  &y);
    void AddOne(int & y)
    void AddOne(int   &     y);
    void AddOne(int&y);
    

    are same!

    0 讨论(0)
提交回复
热议问题