简体   繁体   中英

What should be returned as int& when we don't have a proper lvalue in c++?

Today,My professor wrote this code in his computer:

int& at(int index) {
    if (index < 0 || index >= maxsize){
        cout<<"The index is not valid"<<endl;
        return ;}
    return elements[index];
}

I'm 90 percent sure that the code was exactly the same as above. But when I wrote it in my visual studio 2015 I got error. The compiler wanted me to return an int& in the first return statement. Can you please help me with this?

You could do this:

int global_incorrect_value = 42;

int& at(int index) 
{
    if (index < 0 || index >= maxsize)
    {
        cout<<"The index is not valid"<<endl;
        return global_incorrect_value;
    }
    return elements[index];
}

Or this:

std::optional<int*> at(int index)
{
    if(index < 0 || index >= maxsize)
        return {};
    else
        return &elements[x];
}

Or that:

int* at(int index)
{
    if(index < 0 || index >= maxsize)
        return nullptr;
    else
        return &elements[x];
}

Or even that:

int& at(int index)
{
    if(index < 0 || index >= maxsize)
        throw std::logic_error;
    else
        return elements[x];
}

Or if you are extreme masochist:

int& at(int index)
{
    if(index < 0 || index >= maxsize)
        explode();
    else
        return elements[x];
}

But you cannot do it "like your professor" - posted code is not even close to legal C++.

as I understand the code, I think this function get a value from the array called element and return the value if it found so I will explain my answer in this situation this is a syntax error you don't return anything to a function that returns a value, not void function and should this function not return any value the answer should be in the memory because you return the reference to that value see the example

#include <iostream>
using namespace std;
int elements[10];
int maxsize = 10;
int notFound = -1; // this a value to know that we are access a value out of range so when return -1 we handle it and we write it as a varible not return -1 to have a refrence in memory to return 
int& at(int index) {
    if (index < 0 || index >= maxsize){
        cout<<"The index is not valid"<<endl;
        return notFound; 
    }
    return elements[index];
}

hope this helpful your question is not clear

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM