user7468879
user7468879

Reputation:

Is it possible to return two separate values to a function in this case?

I am trying to determine the minimum number that a user enters into a text file and also the position at which this is found

Attempt at Solution : I have tried the following code to implement minIndex as part of a function which is returning the minimum value correctly :

int minimum(int number, int *minIndex) {

static int minNumber = INT_MAX;
static int index = 0;

if (number < minNumber) {
    minNumber = number;
    *minIndex = index;
}
index++;
return minNumber;
}

EDIT I am then implementing later on:

    int minNumber = 0;
    int finished = 0;
    int minIndex = 0;
    int in = 0;

    for (int i = 1; !finished; i++)
{
    if (fscanf(fp, "%s", word) < 1)
        finished = 1;
    else {
        number = atoi(word);
        minNumber = minimum(number, &in);
        printf("\nstring  is \t %s\n", word);
        printf("integer is \t %d\n", number);
    }
}
printf("min number is %d at position %d\n", minNumber,in);

The minimum number is returned correctly, however minIndex is always shown to be 1.

Is there a problem with my function or is there a more basic issue at hand which I am missing?

Upvotes: 0

Views: 84

Answers (3)

If you want to return two values, you need to return a struct. And I would suggest to just use it entirely to hold the state of your computation instead of the statics.

struct minimum_state {
  int minNumber;
  int minIndex;
  int index;
};

#define MINIMUM_STATE_INIT_VAL \
{ .minNumber = INT_MAX, .minIndex = -1, .index = 0 }

void minimum(int number, struct minimum_state *p_state) {

  if (number < p_state->minNumber) {
    p_state->minNumber = number;
    p_state->minIndex = p_state->index;
  }
  ++(p_state->index);

}

Then your code can be rewritten as follows:

struct minimum_state = MINIMUM_STATE_INIT_VAL;
while(next_number_exists()) {
  minimum(next_number(), &minimum_state);
}

Upvotes: 4

Juan Ignacio Cornet
Juan Ignacio Cornet

Reputation: 239

To be honest, what I would do is to have two functions (single responsability principle).

Then, use your index function and if you want the value, use array[minIndexValue]

So go for option 1, and if you want the minValue, don't call your function, just access to it by it's index

In your case, your code is returning always 1 because it seems that you're iterating all your numbers outside this function, so your index at this function is 1.

Upvotes: 0

chris01
chris01

Reputation: 12321

A function does only return 1 type. Make it a structure and put your 2 integers in it. Or return 1 element and handle one as pointer.

Upvotes: 1

Related Questions