MCS-011 Problem Solving and Programming

First year, Semester 1

Chapters

Newsletter

Declaration & Prototypes

Function Declaration: A function declaration tells the compiler about the function name, return type, and parameters. It is also known as a function prototype. It is usually placed at the beginning of the code or in a header file. This allows the compiler to ensure that function calls match the declared parameters and return type.

Function Prototype: A function prototype specifies the function’s interface without the body of the function. It includes the return type, the function name, and the parameter list with their types.

Example

Here’s a simple example to demonstrate the function declaration and prototype in C:

#include <stdio.h>
// Function prototype void greet(char name[]); int main() { printf("Program started.\n"); // Calling the function greet("Alice"); printf("Program ended.\n"); return 0; } // Function definition void greet(char name[]) { printf("Hello, %s! Welcome to the program!\n", name); }

Explanation

  1. Function Prototype:

    void greet(char name[]);

    This line is the function prototype. It tells the compiler that there is a function named greet that takes a char array (string) as an argument and returns nothing (void). The function prototype is declared before the main function.

  2. Function Call:

    greet("Alice");

    Inside the main function, the greet function is called with the argument "Alice".

  3. Function Definition:

    void greet(char name[]) {
    printf("Hello, %s! Welcome to the program!\n", name); }

    This is the function definition. It provides the actual implementation of the greet function. When greet is called, it prints a welcome message that includes the provided name.

Report an issue

Reporting: Declaration & Prototypes (topic)

Related Posts