ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCC-112Pointers Const Sizeof
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-112

    Programming Fundamentals

    Progress0 / 39 done
    Topics39
    1Introduction to Problem Solving, Algorithms, Programming, and C Language2Problem Solving, a brief review of Von-Neumann Architecture3The C Programming Language, Pseudo-code, Concept of Variable4Data types in Pseudo-code, The C Standard Library and Open Source5Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6Concept of Integer division, Flowchart and its notations7Typical C Program Development Environment, Role of Compiler and Linker8Test Driving C Application
    9A Simple C Program: Printing Text, Adding Two Integer10Memory Concepts, Arithmetic in C, Operators
    11Equality and Relational Operators
    12The if, if...else, while Nested Control Statements
    13for, switch, do...while, break, continue, Logical Operators
    14Modularizing Program in C, Math Library Functions15Function Definitions and Prototypes, Function-Call Stack and Stack Frames16Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration
    18Defining Arrays, Character Arrays, Static and Automatic Local Arrays19Passing Arrays to Function, Sorting and Searching Arrays20Multidimensional and Variable Length Arrays
    21Pointer Definitions and Initialization, Pointer Operators22Passing Arguments to Function by Reference, Using the const and sizeof Operator23Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24Function Pointers
    25Strings and Characters, Character Handling Library26String Functions, Library Functions
    27Streams, Formatted Output with printf, Formatted Input with scanf
    28Defining Structures, Accessing Structure Member, Structures and Functions29typedef, Unions
    30Bitwise Operators, Bit Fields, Enumeration Constants
    31Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File
    32#include, #define, Conditional Compilation, #error and #pragma33# and ## Operators, Predefined Symbolic Constants, Assertions
    34Variable Length Argument List, Using Command Line Arguments35Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36Suffixes for Integer and Floating-Point Literals, Signal Handling
    37calloc and realloc, goto
    38Self-Referential Structures, Linked Lists39Efficiency of Algorithms, Selection and Insertion Sort
    8 min read
    Topic 22 of 39
    Topic Study Note Illustration
    22

    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...

    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 view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    8mremaining
    1.3kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Programming Fundamentals