Coming Soon

This lesson is currently being developed

Introduction to function parameters and arguments

Master passing data to functions through parameters.

C++ Basics: Functions and Files
Chapter
Beginner
Difficulty
50min
Estimated Time

What to Expect

Comprehensive explanations with practical examples

Interactive coding exercises to practice concepts

Knowledge quiz to test your understanding

Step-by-step guidance for beginners

Development Status

In Progress

Content is being carefully crafted to provide the best learning experience

Preview

Early Preview Content

This content is still being developed and may change before publication.

2.4 — Introduction to function parameters and arguments

In this lesson, you'll learn how to pass data to functions using parameters and arguments, understand the difference between the two concepts, and master various parameter-passing techniques.

Parameters vs Arguments

Before diving in, let's clarify two important terms that are often confused:

  • Parameters are the variables declared in the function definition
  • Arguments are the actual values passed to the function when it's called
#include <iostream>

// 'length' and 'width' are parameters
double calculateArea(double length, double width)
{
    return length * width;
}

int main()
{
    double l = 5.0;
    double w = 3.0;
    
    // '5.0' and '3.0' are arguments
    double area1 = calculateArea(5.0, 3.0);
    
    // 'l' and 'w' are also arguments (their values are passed)
    double area2 = calculateArea(l, w);
    
    std::cout << "Area 1: " << area1 << std::endl;
    std::cout << "Area 2: " << area2 << std::endl;
    
    return 0;
}

Output:

Area 1: 15
Area 2: 15

Function parameters

Parameters allow functions to receive input data and customize their behavior. They are declared inside the parentheses of a function:

return_type function_name(type1 parameter1, type2 parameter2, ...)
{
    // function body
}

Single parameter functions

#include <iostream>

double squareNumber(double number)
{
    return number * number;
}

void greetUser(std::string name)
{
    std::cout << "Hello, " << name << "! Nice to meet you." << std::endl;
}

bool isPositive(int value)
{
    return value > 0;
}

int main()
{
    std::cout << "Square of 7: " << squareNumber(7.0) << std::endl;
    greetUser("Alice");
    std::cout << "Is -5 positive? " << (isPositive(-5) ? "Yes" : "No") << std::endl;
    
    return 0;
}

Output:

Square of 7: 49
Hello, Alice! Nice to meet you.
Is -5 positive? No

Multiple parameter functions

Functions can accept multiple parameters of different types:

#include <iostream>

double calculateSimpleInterest(double principal, double rate, int years)
{
    return (principal * rate * years) / 100.0;
}

void displayPersonInfo(std::string firstName, std::string lastName, int age, double height)
{
    std::cout << "Name: " << firstName << " " << lastName << std::endl;
    std::cout << "Age: " << age << " years old" << std::endl;
    std::cout << "Height: " << height << " cm" << std::endl;
}

char determineGrade(int score, int maxScore, bool isExtra)
{
    double percentage = (static_cast<double>(score) / maxScore) * 100;
    
    if (isExtra)
        percentage += 5;  // 5% bonus for extra credit
    
    if (percentage >= 90) return 'A';
    else if (percentage >= 80) return 'B';
    else if (percentage >= 70) return 'C';
    else if (percentage >= 60) return 'D';
    else return 'F';
}

int main()
{
    double interest = calculateSimpleInterest(1000.0, 5.0, 3);
    std::cout << "Interest earned: $" << interest << std::endl;
    
    std::cout << "\nStudent Information:" << std::endl;
    displayPersonInfo("John", "Smith", 20, 175.5);
    
    char grade = determineGrade(85, 100, true);
    std::cout << "\nGrade with extra credit: " << grade << std::endl;
    
    return 0;
}

Output:

Interest earned: $150

Student Information:
Name: John Smith
Age: 20 years old
Height: 175.5 cm

Grade with extra credit: A

How argument passing works

When you call a function with arguments, the values are copied into the function's parameters:

#include <iostream>

void demonstrateParameterCopying(int x, double y)
{
    std::cout << "Inside function:" << std::endl;
    std::cout << "  x = " << x << ", y = " << y << std::endl;
    
    // Modify the parameters
    x = 100;
    y = 99.9;
    
    std::cout << "After modification inside function:" << std::endl;
    std::cout << "  x = " << x << ", y = " << y << std::endl;
}

int main()
{
    int a = 5;
    double b = 3.14;
    
    std::cout << "Before function call:" << std::endl;
    std::cout << "  a = " << a << ", b = " << b << std::endl;
    
    demonstrateParameterCopying(a, b);
    
    std::cout << "After function call:" << std::endl;
    std::cout << "  a = " << a << ", b = " << b << std::endl;  // Original values unchanged!
    
    return 0;
}

Output:

Before function call:
  a = 5, b = 3.14
Inside function:
  x = 5, y = 3.14
After modification inside function:
  x = 100, y = 99.9
After function call:
  a = 5, b = 3.14

Key insight: The original variables a and b remain unchanged because the function receives copies of their values, not the variables themselves.

Parameter order and type matching

Arguments must match the order and type of parameters:

#include <iostream>

void processOrder(std::string customerName, int quantity, double pricePerItem, bool hasDiscount)
{
    double total = quantity * pricePerItem;
    
    if (hasDiscount)
        total = total * 0.9;  // 10% discount
    
    std::cout << "Customer: " << customerName << std::endl;
    std::cout << "Quantity: " << quantity << std::endl;
    std::cout << "Price per item: $" << pricePerItem << std::endl;
    std::cout << "Has discount: " << (hasDiscount ? "Yes" : "No") << std::endl;
    std::cout << "Total: $" << total << std::endl;
}

int main()
{
    // Correct order: string, int, double, bool
    processOrder("Alice Johnson", 3, 25.50, true);
    
    std::cout << "\n---\n" << std::endl;
    
    // Another correct call
    processOrder("Bob Wilson", 1, 75.00, false);
    
    return 0;
}

Output:

Customer: Alice Johnson
Quantity: 3
Price per item: $25.5
Has discount: Yes
Total: $68.85

---

Customer: Bob Wilson
Quantity: 1
Price per item: $75
Has discount: No
Total: $75

Functions with no parameters

Functions can have empty parameter lists:

#include <iostream>

int getRandomNumber()
{
    // Simple pseudo-random number (not truly random)
    static int seed = 12345;
    seed = (seed * 1103515245 + 12345) & 0x7fffffff;
    return seed % 100;  // Return 0-99
}

void displayCurrentTime()
{
    std::cout << "Current time: [Time would be displayed here]" << std::endl;
}

std::string getDefaultMessage()
{
    return "Welcome to our application!";
}

int main()
{
    // Call functions with no parameters
    int random = getRandomNumber();
    std::cout << "Random number: " << random << std::endl;
    
    displayCurrentTime();
    
    std::string message = getDefaultMessage();
    std::cout << "Message: " << message << std::endl;
    
    return 0;
}

Output:

Random number: 45
Current time: [Time would be displayed here]
Message: Welcome to our application!

Mixed parameter types and practical examples

Let's look at more complex examples with mixed parameter types:

#include <iostream>

// Game character creation
void createCharacter(std::string name, int level, double health, double mana, bool isPlayer)
{
    std::cout << "=== Character Created ===" << std::endl;
    std::cout << "Name: " << name << std::endl;
    std::cout << "Level: " << level << std::endl;
    std::cout << "Health: " << health << "/" << health << std::endl;
    std::cout << "Mana: " << mana << "/" << mana << std::endl;
    std::cout << "Type: " << (isPlayer ? "Player" : "NPC") << std::endl;
    std::cout << "=========================" << std::endl;
}

// Mathematical calculation with multiple parameters
double calculateCompoundInterest(double principal, double rate, int compounds, int years)
{
    double result = principal;
    double ratePerPeriod = rate / (100.0 * compounds);
    int totalPeriods = compounds * years;
    
    for (int i = 0; i < totalPeriods; ++i)
    {
        result *= (1.0 + ratePerPeriod);
    }
    
    return result - principal;  // Return only the interest earned
}

// Text formatting function
void formatMessage(std::string message, char border, int width, bool centered)
{
    // Print top border
    for (int i = 0; i < width; ++i)
        std::cout << border;
    std::cout << std::endl;
    
    // Print message
    if (centered && message.length() < width - 2)
    {
        int padding = (width - 2 - static_cast<int>(message.length())) / 2;
        std::cout << border;
        for (int i = 0; i < padding; ++i)
            std::cout << " ";
        std::cout << message;
        for (int i = 0; i < width - 2 - padding - static_cast<int>(message.length()); ++i)
            std::cout << " ";
        std::cout << border << std::endl;
    }
    else
    {
        std::cout << border << " " << message;
        for (int i = 0; i < width - 3 - static_cast<int>(message.length()); ++i)
            std::cout << " ";
        std::cout << " " << border << std::endl;
    }
    
    // Print bottom border
    for (int i = 0; i < width; ++i)
        std::cout << border;
    std::cout << std::endl;
}

int main()
{
    createCharacter("Gandalf", 50, 100.0, 200.0, false);
    
    std::cout << std::endl;
    
    double interest = calculateCompoundInterest(1000.0, 5.0, 4, 2);
    std::cout << "Compound interest earned: $" << interest << std::endl;
    
    std::cout << std::endl;
    
    formatMessage("Hello World", '*', 30, true);
    formatMessage("Welcome to C++", '#', 25, false);
    
    return 0;
}

Output:

=== Character Created ===
Name: Gandalf
Level: 50
Health: 100/100
Mana: 200/200
Type: NPC
=========================

Compound interest earned: $104.081

******************************
*         Hello World        *
******************************
#########################
# Welcome to C++         #
#########################

Best practices for parameters

✅ Good practices:

// 1. Use descriptive parameter names
double calculateBMI(double weightInKg, double heightInMeters)
{
    return weightInKg / (heightInMeters * heightInMeters);
}

// 2. Order parameters logically (most important first, related parameters together)
void drawRectangle(int width, int height, char fillChar = '*')
{
    // width and height are related and come first
    // fillChar is optional with default value
}

// 3. Keep the parameter count reasonable (usually 5 or fewer)
void processPayment(double amount, std::string customerName, std::string cardNumber)
{
    // Clear, focused purpose with few parameters
}

// 4. Use const for parameters that shouldn't be modified (advanced topic)
void displayUserInfo(const std::string& userName, const int& userId)
{
    std::cout << "User: " << userName << " (ID: " << userId << ")" << std::endl;
}

❌ Avoid these patterns:

// Don't use unclear parameter names
double calc(double a, double b, double c)  // What do a, b, c represent?
{
    return a / (b * b);
}

// Don't use too many parameters
void messyFunction(int a, int b, int c, int d, int e, int f, int g, int h)
{
    // Too many parameters make the function hard to use
}

// Don't put unrelated parameters together
void confusingFunction(std::string name, double temperature, bool isStudent, int age)
{
    // These parameters don't seem related to a single purpose
}

Common parameter patterns

1. Input validation pattern

#include <iostream>

double safeDivide(double numerator, double denominator)
{
    if (denominator == 0.0)
    {
        std::cout << "Error: Division by zero!" << std::endl;
        return 0.0;  // or throw an exception in real applications
    }
    return numerator / denominator;
}

int main()
{
    std::cout << "10 / 2 = " << safeDivide(10.0, 2.0) << std::endl;
    std::cout << "10 / 0 = " << safeDivide(10.0, 0.0) << std::endl;
    
    return 0;
}

2. Configuration pattern

#include <iostream>

void configureDisplay(int width, int height, bool fullscreen, int colorDepth)
{
    std::cout << "Configuring display:" << std::endl;
    std::cout << "  Resolution: " << width << "x" << height << std::endl;
    std::cout << "  Fullscreen: " << (fullscreen ? "Yes" : "No") << std::endl;
    std::cout << "  Color depth: " << colorDepth << " bits" << std::endl;
}

int main()
{
    configureDisplay(1920, 1080, true, 32);
    
    return 0;
}

3. Calculation pattern

#include <iostream>

double calculateDistance(double x1, double y1, double x2, double y2)
{
    double dx = x2 - x1;
    double dy = y2 - y1;
    return std::sqrt(dx * dx + dy * dy);  // Would need #include <cmath>
}

int main()
{
    // Calculate distance between two points
    double distance = calculateDistance(0.0, 0.0, 3.0, 4.0);
    std::cout << "Distance: " << distance << std::endl;
    
    return 0;
}

Summary

Function parameters and arguments are fundamental to creating flexible, reusable functions:

Key concepts:

  • Parameters are declared in the function definition
  • Arguments are the values passed when calling the function
  • Arguments are copied into parameters (pass by value)
  • Parameter order and types must match the function definition
  • Functions can have zero or many parameters

Best practices:

  • Use descriptive parameter names
  • Keep parameter counts reasonable
  • Order parameters logically
  • Validate input parameters when necessary
  • Consider the purpose and focus of each function

Quiz

  1. What's the difference between a parameter and an argument?
  2. What happens to the original variables when you pass them as arguments to a function?
  3. Do arguments need to match the order of parameters?
  4. Can a function have zero parameters?
  5. What would happen if you called calculateArea(5.0) for a function that expects two parameters?

Practice exercises

Try implementing these functions:

  1. double calculateTriangleArea(double base, double height) - Calculate triangle area
  2. void displayBox(int width, int height, char borderChar) - Draw a box with given dimensions
  3. int findMaximum(int num1, int num2, int num3) - Return the largest of three numbers
  4. bool isValidEmailFormat(std::string email, int minLength, bool requireAt) - Basic email validation

Continue Learning

Explore other available lessons while this one is being prepared.

View Course

Explore More Courses

Discover other available courses while this lesson is being prepared.

Browse Courses

Lesson Discussion

Share your thoughts and questions

💬

No comments yet. Be the first to share your thoughts!

Sign in to join the discussion