Add Numbers in C Without Using Return Statement
In C, normally functions return a value using the 'return' keyword. However, it is possible to get results back to main() without using 'return' by using pointers or passing variables by reference.
This technique modifies the value of a variable in main() directly from the function.
Method: Using Pointers (Call by Reference)
1. Declare a function with void return type.
2. Pass the address of the variable to the function.
3. Inside the function, store the result in the memory location pointed by the pointer.
C Program to Add Two Numbers Without Using Return
#include <stdio.h>
void addNumbers(int a, int b, int *sum) {
*sum = a + b; // Store result at the memory address provided
}
int main() {
int num1, num2, result;
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
// Pass address of result to the function
addNumbers(num1, num2, &result);
printf("Sum = %d\n", result);
return 0;
}
Sample Input: Enter first number: 10 Enter second number: 15 Output: Sum = 25
Explanation
1. The function 'addNumbers' has void return type and three parameters: two integers and a pointer to integer.
2. The sum is calculated inside the function and stored in the memory location pointed by 'sum'.
3. In main(), we pass the address of 'result' using '&result'. The value is updated directly.
4. This avoids using the 'return' keyword but still returns the computed value to main().
Advantages
• Avoids returning value explicitly.
• Useful for functions that need to modify multiple variables.
• Demonstrates use of pointers and call by reference.
Conclusion
Using pointers, we can add two numbers in a function and return the result to main() without using the 'return' keyword.
This approach is helpful for passing multiple results or modifying variables directly in calling functions.
Codecrown