Why does this code not work Obviously the return statement i
Why does this code not work? Obviously the return statement is never reached because I keep getting an error that there is no return statement.
// REQUIRES: mat points to a valid Matrix
// ptr points to an element in the Matrix
// EFFECTS: Returns the row of the element pointed to by ptr.
int Matrix_row(const Matrix* mat, const int* ptr) {
for (int r = 0; r < (mat->height); r++) {
for (int c = 0; c < (mat->width); c++) {
if (ptr == (&mat->data[((mat->width) * r) + c])) {
return r;
}
}
}
}
Solution
Answer:
you have written a return statement in if block. If block executes then return statement will return the value. Let us assume If condition is met then return statement will not execute. So we have to provide anothe return statement to method level. If your condition does not meet then method level return statement will return the value.
I updatd the code and highlighted the code changes below
int Matrix_row(const Matrix* mat, const int* ptr) {
for (int r = 0; r < (mat->height); r++) {
for (int c = 0; c < (mat->width); c++) {
if (ptr == (&mat->data[((mat->width) * r) + c])) {
return r;
}
}
}
return -1;
}
