Am I doing something wrong here (C ++ links)?

I played with links (I still have problems in this regard).

1- I would like to know if this is acceptable code:

int & foo(int &y)
{
    return y;  // is this wrong?
}

int main()
{
    int x = 0;    
    cout << foo(x) << endl;

    foo(x) = 9;   // is this wrong?
    cout << x << endl;

    return 0;
}

2- Also this is from an exam example:

Week & Week::highestSalesWeek(Week aYear[52])
{
  Week max = aYear[0];
  for(int i = 1; i < 52; i++)
  {
    if (aYear[i].getSales() > max.getSales())
      max = aYear[i];
  }
  return max;
}

He asks for an error in this code, as well as how to fix it.

I assume it returns a local link. Correction:

Week & max = aYear[0];

Is this correct / sufficient?

+5
source share
3 answers

The first one is correct.

For the second, there are an infinite number of solutions :), but that would be mine:

Week Week::highestSalesWeek(Week aYear[52]) // return a copy of the week
{ 
  Week max = aYear[0]; 
  for(int i = 1; i < 52; i++) 
  { 
    if (aYear[i].getSales() > max.getSales()) max = aYear[i]; 
  } 
  return max; 
} 

If max is a link, you change the first aYear element every time:

max = aYear[i]

Alternatively, you can use the pointer to return the link for the week:

Week & Week::highestSalesWeek(Week aYear[52])
{ 
  Week* max = &aYear[0]; 
  for(int i = 1; i < 52; i++) 
  { 
    if (aYear[i].getSales() > max->getSales()) max = &aYear[i]; 
  } 
  return *max; 
} 
+5
source

, , .

:

Week & Week::highestSalesWeek(Week aYear[52])
{
  Week max = aYear[0];
  return max;
}

max - , . , max , .

max, ( , , ). aYear, . .

// By pointer
Week & Week::highestSalesWeek(Week aYear[52])
{
  Week *max = &aYear[0];
  ...;
  return *max;
}

// By index
Week & Week::highestSalesWeek(Week aYear[52])
{
  size_t max_idx = 0;;
  ...;
  return aYear[max_idx];
}    
+2

:

foo(x) = 9;   // is this wrong?

, , , , . "" ( ?):

Week & Week::highestSalesWeek(Week aYear[52])
{
  Week max = aYear[0];
  for(int i = 1; i < 52; i++)
  {
    if (aYear[i].getSales() > max.getSales()) max = aYear[i];
  }
  return max;
}

Well, provided that the size of the array in the parameter is meaningless, and the code must explicitly use the vector. And the fix should be in the function signature:

Week  Week::highestSalesWeek(Week aYear[52])

In other words, return the value. You should almost always return values, not links - links are for function parameters.

+1
source

All Articles