/******************************************************************************
Online C Compiler.
Code, Compile, Run and Debug C program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
// Define the Error structure
typedef struct Error {
int errorCode;
char errorMessage[100];
struct Error *next;
} Error;
// Function to create a new Error node
Error* createError(int code, const char* message) {
Error *newError = (Error*)malloc(sizeof(Error));
if (newError == NULL) {
fprintf(stderr, "Memory allocation failed.\n");
exit(EXIT_FAILURE);
}
newError->errorCode = code;
strncpy(newError->errorMessage, message, sizeof(newError->errorMessage));
newError->next = NULL;
return newError;
}
// Function to insert an Error node at the beginning of the list
void insertError(Error **head, int code, const char* message) {
Error *newError = createError(code, message);
newError->next = *head;
*head = newError;
}
// Function to print all Errors in the linked list
void printErrors(Error *head) {
Error *current = head;
while (current != NULL) {
printf("Error Code: %d, Message: %s\n", current->errorCode, current->errorMessage);
current = current->next;
}
}
// Function to free the entire linked list
void freeErrors(Error *head) {
Error *current = head;
while (current != NULL) {
Error *temp = current;
current = current->next;
free(temp);
}
}
// Define a struct to hold the result and error information
struct DoubleResult {
double value; // Result
Error *error; // Error
};
struct DoubleResult divide(double a, double b, Error *head) {
struct DoubleResult result;
if (a >= INT_MAX) {
// catch first error
insertError(&head, 100, "Value a is overflow");
}
if (b == 0) {
// catch second error
insertError(&head, 101, "Division by zero");
}
if (a >= INT_MAX || b == 0) {
// errors
result.error = head;
result.value = -1; // default if error
return result;
}
// success
result.error = NULL; // default if success
result.value = a/b;
return result;
}
int main() {
Error *head = NULL;
// example 1
printf("divide(INT_MAX, 0)\n");
struct DoubleResult result1 = divide(INT_MAX, 0, head);
if(result1.error == NULL) {
// success
printf("result %.f\n", result1.value);
}
else {
// error
printErrors(result1.error);
}
printf("\n");
// example 2
printf("divide(10, 2)\n");
struct DoubleResult result2 = divide(10, 2, head);
if(result2.error == NULL) {
// success
printf("result %.f\n", result2.value);
}
else {
// error
printErrors(result2.error);
}
// Free the allocated memory
freeErrors(head);
return 0;
}
Result:
divide(INT_MAX, 0)
Error Code: 101, Message: Division by zero
Error Code: 100, Message: Value a is overflow
divide(10, 2)
result 5
list
assigned/initialized prior to the firstfoo()
call?