C return statement
Created By: chatGPT
C provides a return statement that is crucial for function operations. It signifies the end of a function and optionally returns a value to the calling function. Here's a breakdown of how to use it effectively.
int add(int a, int b) {
return a + b;
}
In this example, we defined a function named add that takes two integers as parameters. The return keyword sends back the sum of these integers to the caller.
int main() {
int result;
result = add(5, 3);
printf("The result is: %d\n", result);
return 0;
}
The main function is the entry point of the program. Here, we call the add function and store the result. Finally, we print the result using printf.
#include <stdio.h>
int main() {
int result;
result = add(5, 3);
printf("The result is: %d\n", result);
return 0;
}
It's important to note that a function with a return type must return a value of the specified type when the return statement is executed. If a function is declared to return void, no return value should be provided.
void displayMessage() {
printf("Hello, World!\n");
}
In this void function, we simply print a message without returning any value. Using a return statement in such a function would result in a compilation error.
void displayMessage() {
printf("Hello, World!\n");
return; // This is optional and can be omitted.
}