0

I'm learning modern C++ and sometimes I see values passed by reference written slightly differently with a space.

int &i

Is there a difference?

int& x

#include <iostream>
using namespace std;

void swapnum(int &i, int &j) {
  int temp = i;
  i = j;
  j = temp;
}

void f(const int& x) {
  int& y = const_cast<int&>(x);
  ++y;
}
Alison
  • 107
  • 1
  • 8
  • 3
    No, the spacing makes no difference at all. – iBug Sep 30 '18 at 09:05
  • 2
    I assume you are referring to the ampersand `&` position? No, there is no semantic difference. – freakish Sep 30 '18 at 09:06
  • 1
    Same as mentioned in the duplicate applies for the `&`. – πάντα ῥεῖ Sep 30 '18 at 09:07
  • The const, on the other hand, does make a difference. Wouldn't be surprised if your `f()` function causes undefined behavior the way it modifies a value obtained from a const reference. – Shawn Sep 30 '18 at 09:08
  • If you're not asking about the difference with the `const` specifier, then please *remove it*. It's irrelevant to your question and confusing. – Some programmer dude Sep 30 '18 at 09:09
  • 5
    Also note that what your function `f` is doing is ***bad***. If the argument passed to `f` is indeed a constant (one way or another) then the function will lead to [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior). Don't cast away `const` unless you 100% know it's safe. – Some programmer dude Sep 30 '18 at 09:11
  • Funny you say that. It came from this link. I would agree too when I saw it but I just used it to ask my question. https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.3.0/com.ibm.zos.v2r3.cbclx01/cplr233.htm – Alison Sep 30 '18 at 09:16
  • As far as the compiler is concerned, there is no difference. As far as I am concerned, the first drives me into a furious indignant rage, and the second makes me happy. – Eljay Sep 30 '18 at 11:55

1 Answers1

3

No, the spacing makes no difference at all. What makes the difference in your example is the const keyword (which isn't the question here).

Spacing doesn't really matter, except your colleagues may complain about bad styling. These forms are equivalent to the compiler:

int &i;
int& i;
int&i;
int
&
i;

The compiler will parse the code into "lexical elements" before further processing, and space only serves as separators.

iBug
  • 35,554
  • 7
  • 89
  • 134