Multiple Error Codes
C
Hard
2 views
Problem Description
Create a function that can return different error types: success=0, null_pointer=-1, out_of_bounds=-2, invalid_input=-3. Use enums for readability.
Official Solution
#include <stdio.h>
typedef enum {
SUCCESS = 0,
NULL_POINTER = -1,
OUT_OF_BOUNDS = -2,
INVALID_INPUT = -3
} ErrorCode;
/*
* Example function:
* - data: pointer to an int array
* - size: size of the array
* - index: index to access
* - out: pointer to store the result
*/
ErrorCode get_value(const int *data, int size, int index, int *out)
{
if (data == NULL || out == NULL) {
return NULL_POINTER;
}
if (size <= 0) {
return INVALID_INPUT;
}
if (index < 0 || index >= size) {
return OUT_OF_BOUNDS;
}
*out = data[index];
return SUCCESS;
}
/* Example usage */
int main(void)
{
int arr[] = {10, 20, 30};
int value;
ErrorCode result = get_value(arr, 3, 1, &value);
if (result == SUCCESS) {
printf("Value: %dn", value);
} else {
printf("Error code: %dn", result);
}
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!