C functions
Created By: chatGPT
C functions are blocks of code that perform a specific task. They allow you to break your program into smaller, manageable pieces, which can be reused throughout your code. Each function can take inputs, perform operations, and return values. Let's look at the structure of a simple function.
return_type function_name(parameter_type parameter_name) {
// Function body
return value; // Optional if the function is void
}
The above structure defines a function with a specified return type, a name, and a set of input parameters. For instance, a function that adds two integers could look like this:
int add(int a, int b) {
return a + b;
}
In this example, the function
add
takes two integers as parameters, adds them, and returns their sum. Functions can also be void, meaning they do not return a value. Here’s how you could define a function that prints a message:void print_message() {
printf("Hello, World!\n");
}
You can call functions from within your main program or other functions. To use the
add
function in your main
function, the code would look like this:int main() {
int sum = add(5, 10);
printf("Sum: %d\n", sum);
return 0;
}
Local and global variables are important concepts when working with functions. Local variables are defined within a function and are not accessible outside, while global variables are defined outside any function and can be accessed by any function in the program. For example:
Using functions effectively can lead to better organization and maintainability of your code. Remember that functions can also call other functions, which makes it easier to manage complex operations. By using parameters and return values, you can create versatile and reusable code components.int global_var = 10;
void display_global() {
printf("Global Variable: %d\n", global_var);
}
int main() {
display_global();
return 0;
}