0

I have the following function written in c and working properly; but I need to convert it to c#. There is variable called unsigned int found_at = -1 ; the equivalent in c# should be uint found_at = -1; However I receive compiler error. Could you please guide me to solve this problem

unsigned int find_adjacent_values(double val, unsigned int start_here, unsigned int end_here, double *vector) {
unsigned int i = start_here, found = 0, found_at = -1;
while (i < end_here-1 && found == 0) {
    if (val >= vector[i] && val < vector[i+1]) { // check whether we found adjacent values
        found = 1;
        found_at = i;
    } else {
        i += 1;
    }
}
return found_at;

}

  • 1
    Why not just use `int`? That would cover all possible index values and -1. – juharr Jan 24 '21 at 22:06
  • 1
    Assigning `-1` to an unsigned value is just bad practice in both languages. The intent is to write `UINT_MAX` in C, or `uint.MaxValue` in C#. – jwdonahue Jan 24 '21 at 22:08

1 Answers1

1

Try:

uint found_at = unchecked((uint)-1);

Note that thanks to how two's complement numbers work, that line is equivalent to writing:

uint found_at = uint.MaxValue;

The explanation about why you need the unchecked(...) is here.

xanatos
  • 109,618
  • 12
  • 197
  • 280