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›Passing Arguments to Function by Reference, Using the const and sizeof Operator
    Programming FundamentalsTopic 22 of 39

    Passing Arguments to Function by Reference, Using the const and sizeof Operator

    8 minread
    1,288words
    Intermediatelevel

    Passing Arguments to Function by Reference, Using the const and sizeof` Operator

    In C programming, you can pass arguments to functions in multiple ways, with two of the most important being passing by reference and using the const and sizeof operators. Each of these concepts plays a key role in making your code more flexible, efficient, and readable.

    Let’s break down passing arguments by reference, using the const keyword, and using the sizeof operator in detail.


    1. Passing Arguments to Function by Reference

    When you pass an argument to a function by reference, you pass the memory address (reference) of the variable rather than a copy of the variable itself. This allows the function to modify the original variable’s value. In C, pointers are used for passing arguments by reference.

    How It Works

    • Pass by Value: A copy of the actual value is passed to the function. Any modification made to the parameter inside the function does not affect the original variable.
    • Pass by Reference: The memory address of the variable is passed to the function. The function can directly modify the value at that memory address, and the changes reflect in the original variable.

    Syntax for Passing by Reference

    void function_name(type *parameter) {
        // function body
    }
    
    • *parameter: The parameter is a pointer that holds the address of the actual variable passed to the function.

    Example: Passing by Reference

    #include <stdio.h>
    
    void swap(int *a, int *b) {
        // Swapping the values using references (pointers)
        int temp = *a;
        *a = *b;
        *b = temp;
    }
    
    int main() {
        int x = 5, y = 10;
        printf("Before swap: x = %d, y = %d\n", x, y);
    
        // Pass the addresses of x and y
        swap(&x, &y);
    
        printf("After swap: x = %d, y = %d\n", x, y);
    
        return 0;
    }
    

    Explanation:

    • In the swap function, we pass the addresses of x and y using the & operator (&x and &y).
    • The pointers a and b now point to x and y, respectively.
    • Using dereferencing (*a and *b), we swap the values of x and y.

    Output:

    Before swap: x = 5, y = 10
    After swap: x = 10, y = 5
    

    Here, the original variables x and y were modified within the function because we passed their addresses, which allows direct modification of their values.


    2. Using the const Keyword

    The const keyword is used to declare variables whose value should not be changed after initialization. It is commonly used with pointers to ensure that the data pointed to by the pointer cannot be modified. This is particularly useful when passing pointers to functions and ensuring that the data remains constant.

    Const with Pointers

    • Pointer to Constant: A pointer to a constant means the data being pointed to cannot be modified, but the pointer itself can point to different memory locations.

      const int *ptr;
      
    • Constant Pointer: A constant pointer means the pointer itself cannot point to a different memory location, but the data it points to can be modified.

      int * const ptr;
      
    • Constant Pointer to Constant: A constant pointer that points to constant data. Neither the pointer can be changed, nor the data it points to can be modified.

      const int * const ptr;
      

    Example: Using const with Function Arguments

    #include <stdio.h>
    
    void printValue(const int *ptr) {
        // Cannot modify the value pointed to by ptr
        printf("Value: %d\n", *ptr);
        // *ptr = 20;  // Error: Cannot modify the value of a const pointer
    }
    
    int main() {
        int x = 10;
        printValue(&x);
    
        return 0;
    }
    

    Explanation:

    • The parameter const int *ptr ensures that the value pointed to by ptr cannot be modified inside the function.
    • Attempting to modify the value via *ptr will result in a compilation error.

    Output:

    Value: 10
    

    Here, the function safely reads the value of x but does not modify it, as ptr is a pointer to constant data.


    3. Using the sizeof Operator

    The sizeof operator is a compile-time operator used to determine the size (in bytes) of a data type or variable. This operator is very useful in memory management, dynamic memory allocation, and determining the size of arrays or structures.

    Syntax:

    sizeof(type)          // Size of a data type
    sizeof(expression)    // Size of a variable or expression
    

    Examples:

    • Size of a Data Type:
    #include <stdio.h>
    
    int main() {
        printf("Size of int: %zu bytes\n", sizeof(int));  // Size of int
        printf("Size of char: %zu bytes\n", sizeof(char));  // Size of char
        printf("Size of double: %zu bytes\n", sizeof(double));  // Size of double
    
        return 0;
    }
    
    • Size of an Array:
    #include <stdio.h>
    
    int main() {
        int arr[10];
        printf("Size of arr: %zu bytes\n", sizeof(arr));  // Total size of the array
        printf("Size of each element in arr: %zu bytes\n", sizeof(arr[0]));  // Size of one element
    
        return 0;
    }
    

    Explanation:

    • sizeof(int) returns the size of the int data type, which is typically 4 bytes on most systems.
    • sizeof(arr) returns the total size of the array arr (which is the size of the type multiplied by the number of elements).
    • sizeof(arr[0]) returns the size of a single element of the array (which in this case is the size of an int).

    Output:

    Size of int: 4 bytes
    Size of char: 1 byte
    Size of double: 8 bytes
    Size of arr: 40 bytes
    Size of each element in arr: 4 bytes
    

    Here:

    • sizeof(arr) gives the total size of the array (40 bytes for 10 integers of 4 bytes each).
    • sizeof(arr[0]) gives the size of one element in the array (int), which is 4 bytes.

    Practical Use of sizeof:

    sizeof is extremely useful when dynamically allocating memory. For example, when allocating memory for an array using malloc, you can use sizeof to allocate memory for the correct amount of data:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        int n;
        printf("Enter number of elements: ");
        scanf("%d", &n);
    
        // Dynamically allocate memory for 'n' integers
        int *arr = (int *)malloc(n * sizeof(int));
    
        if (arr == NULL) {
            printf("Memory allocation failed.\n");
            return 1;
        }
    
        printf("Memory allocated for %d integers.\n", n);
    
        // Remember to free the allocated memory when done
        free(arr);
    
        return 0;
    }
    

    Explanation:

    • malloc(n * sizeof(int)) dynamically allocates memory for n integers.
    • sizeof(int) ensures the correct amount of memory is allocated for each int type.

    4. Summary of Key Concepts

    • Passing Arguments by Reference: Use pointers to pass the memory address of a variable to a function, allowing the function to modify the original variable’s value.

    • Using const: The const keyword ensures that data cannot be modified. It can be used with pointers to ensure that the pointer does not modify the data it points to or to ensure the pointer itself cannot point to a different memory location.

    • Using sizeof: The sizeof operator returns the size of a data type or variable in bytes, which is essential for dynamic memory allocation and array manipulation.

    These features are fundamental in C programming and enable more efficient, flexible, and robust code. Understanding how to properly use pointers, const, and sizeof can improve your ability to manage memory and handle data in complex C applications.

    Previous topic 21
    Pointers: Pointer Definitions and Initialization, Pointer Operators
    Next topic 23
    Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers

    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 time8 min
      Word count1,288
      Code examples0
      DifficultyIntermediate