ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Programming Fundamentals
    CC-112
    Progress0 / 39 topics
    Topics
    1. Introduction to Problem Solving, Algorithms, Programming, and C Language2. Problem Solving, a brief review of Von-Neumann Architecture3. The C Programming Language, Pseudo-code, Concept of Variable4. Data types in Pseudo-code, The C Standard Library and Open Source5. Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6. Concept of Integer division, Flowchart and its notations7. Typical C Program Development Environment, Role of Compiler and Linker8. Test Driving C Application9. Introduction to C Programming: A Simple C Program: Printing Text, Adding Two Integer10. Memory Concepts, Arithmetic in C, Operators11. Decision Making: Equality and Relational Operators12. Structured Program Development: The if, if...else, while Nested Control Statements13. Program Control: for, switch, do...while, break, continue, Logical Operators14. Functions: Modularizing Program in C, Math Library Functions15. Function Definitions and Prototypes, Function-Call Stack and Stack Frames16. Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17. Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration18. Arrays: Defining Arrays, Character Arrays, Static and Automatic Local Arrays19. Passing Arrays to Function, Sorting and Searching Arrays20. Multidimensional and Variable Length Arrays21. Pointers: Pointer Definitions and Initialization, Pointer Operators22. Passing Arguments to Function by Reference, Using the const and sizeof Operator23. Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24. Function Pointers25. Characters and Strings: Strings and Characters, Character Handling Library26. String Functions, Library Functions27. Formatted Input/Output: Streams, Formatted Output with printf, Formatted Input with scanf28. Structures: Defining Structures, Accessing Structure Member, Structures and Functions29. typedef, Unions30. Bit Manipulation and Enumeration: Bitwise Operators, Bit Fields, Enumeration Constants31. File Processing: Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File32. Preprocessor: #include, #define, Conditional Compilation, #error and #pragma33. # and ## Operators, Predefined Symbolic Constants, Assertions34. Other Topics: Variable Length Argument List, Using Command Line Arguments35. Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36. Suffixes for Integer and Floating-Point Literals, Signal Handling37. Dynamic Memory Allocation: calloc and realloc, goto38. Advance Topics: Self-Referential Structures, Linked Lists39. Efficiency of Algorithms, Selection and Insertion Sort
    CC-112›Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference
    Programming FundamentalsTopic 16 of 39

    Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference

    6 minread
    1,051words
    Intermediatelevel

    Stack Rolling and Unrolling

    Stack rolling and stack unrolling refer to the process of managing the stack memory during function calls, especially in recursive functions.

    Stack Rolling

    Stack rolling happens when a function is called and a new stack frame is created to hold that function's parameters, local variables, and return address. This process is sometimes referred to as "pushing" onto the stack because each new function call pushes a new frame onto the stack.

    Example:

    #include <stdio.h>
    
    void functionA() {
        int a = 10;  // Local variable
        printf("Inside functionA\n");
    }
    
    void functionB() {
        functionA();  // functionA is called, creating a new stack frame
    }
    
    int main() {
        functionB();  // functionB calls functionA, and the stack rolls
        return 0;
    }
    
    • When functionB() calls functionA(), the stack rolls (a new stack frame for functionA() is pushed onto the stack).
    • The stack frame will store the local variables and return address for functionA().

    Stack Unrolling

    Stack unrolling is the reverse process of stack rolling. When a function call is completed, its stack frame is removed from the call stack (popped), and control returns to the calling function. This process is essential for cleaning up memory and maintaining the correct execution flow.

    Example of Stack Unrolling:

    #include <stdio.h>
    
    void functionA() {
        printf("Inside functionA\n");
    }
    
    int main() {
        functionA();  // After functionA finishes, stack unrolling occurs
        return 0;
    }
    
    • After functionA() completes, its stack frame is popped off the stack, and execution returns to main().

    Recursion and Stack Management

    In recursive functions, stack rolling and unrolling occur repeatedly as functions call themselves. Every recursive call creates a new stack frame, and when the recursion reaches the base case, the function begins returning, causing the stack to unroll.

    #include <stdio.h>
    
    void recursive(int n) {
        if (n > 0) {
            printf("%d\n", n);
            recursive(n - 1);  // Recursive call, rolling the stack
        }
    }
    
    int main() {
        recursive(3);  // Calls recursive(3), which rolls the stack
        return 0;
    }
    
    • When recursive(3) calls recursive(2), the stack rolls.
    • When n reaches 0, the recursion starts to return, and the stack begins to unroll.

    Headers in C

    In C programming, headers are files that typically contain declarations of functions, macros, constants, and types. These files allow functions and variables to be used in multiple source files by providing a way to declare interfaces between different parts of a program.

    Header Files

    A header file typically has a .h extension and contains:

    • Function Prototypes: Declares functions that will be defined elsewhere.
    • Macros: Defines constants or expressions that can be used throughout the program.
    • Data Structures: Declares structs, enums, etc.

    For example, the header file math.h provides functions like sin(), cos(), etc., for mathematical operations.

    Example of a Custom Header File:
    // math_operations.h
    #ifndef MATH_OPERATIONS_H
    #define MATH_OPERATIONS_H
    
    int add(int a, int b);   // Function prototype for add
    int subtract(int a, int b);  // Function prototype for subtract
    
    #endif
    
    // main.c
    #include <stdio.h>
    #include "math_operations.h"  // Including the custom header file
    
    int main() {
        int sum = add(3, 5);
        int diff = subtract(10, 4);
        printf("Sum: %d, Difference: %d\n", sum, diff);
        return 0;
    }
    

    In this example:

    • The header file math_operations.h contains the function prototypes for add() and subtract().
    • main.c includes this header and calls the functions.

    Passing Arguments by Value and by Reference

    In C, functions can accept arguments in two primary ways: by value and by reference. The distinction is crucial for understanding how data is passed between functions and whether modifications to arguments affect the calling function's variables.

    Passing Arguments by Value

    When arguments are passed by value, a copy of the variable is passed to the function. This means that any changes made to the parameter inside the function do not affect the original variable.

    Example:

    #include <stdio.h>
    
    void byValue(int x) {
        x = 10;  // Modifying the local copy of x
    }
    
    int main() {
        int num = 5;
        byValue(num);
        printf("num after byValue: %d\n", num);  // num remains 5
        return 0;
    }
    
    • Here, num is passed by value to the function byValue(). The x inside byValue() is a copy of num, so changes to x don't affect the original num.

    Passing Arguments by Reference

    When arguments are passed by reference, the function receives the address (memory location) of the variable, not a copy. This means that changes to the parameter inside the function directly affect the original variable.

    In C, we typically simulate passing by reference using pointers.

    Example:

    #include <stdio.h>
    
    void byReference(int *x) {
        *x = 10;  // Modifying the value at the address pointed to by x
    }
    
    int main() {
        int num = 5;
        byReference(&num);  // Passing the address of num
        printf("num after byReference: %d\n", num);  // num is now 10
        return 0;
    }
    
    • Here, num is passed by reference to the function byReference() by passing its memory address using the & operator. Inside the function, the value at that memory address is modified, so the change is reflected in the original variable num.

    Summary

    1. Stack Rolling and Unrolling:

      • Stack Rolling occurs when a new stack frame is created for a function call.
      • Stack Unrolling happens when a function finishes execution and its stack frame is removed.
      • This is essential for handling function calls, especially in recursion.
    2. Headers:

      • Header files in C contain declarations for functions, macros, and types.
      • They allow you to share function prototypes and definitions across multiple files in a project.
      • Example: #include <stdio.h> or #include "my_header.h".
    3. Passing Arguments by Value and by Reference:

      • By Value: A copy of the argument is passed, and changes to it don't affect the original variable.
      • By Reference: The address of the argument is passed (using pointers), and changes affect the original variable.

    Understanding these concepts is fundamental to managing memory, working with functions, and efficiently passing data between different parts of a C program.

    Previous topic 15
    Function Definitions and Prototypes, Function-Call Stack and Stack Frames
    Next topic 17
    Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time6 min
      Word count1,051
      Code examples0
      DifficultyIntermediate