Why is sizeof() or sizeof called an operator, not a function in C ?

Why is sizeof() or sizeof called an operator, not a function in C ?

The sizeof() or sizeof is an operator rather than a function in C? computer programming language for several reasons:

  • Compile-Time Evaluation: The sizeof operator is evaluated at compile time, rather than getting executed at runtime like functions.?
  • Syntax and Usage: sizeof can be used with or without parentheses, unlike functions which always require parenthesis. Please note the following piece of codes in C?

Example 1:
#include <stdio.h>

int main() {
  int num=5;
  printf("1. size of num : %zu\n", sizeof(num)); // sizeof operator with parentheses ()
  printf("2. size of num : %zu\n", sizeof num ); // sizeof operator without parentheses
  return 0;
}
/*
OUTPUT:
1. size of num : 4
2. size of num : 4
*/        
Example 2:
#include <stdio.h>

int main() {

/* sizeof operator with parentheses () always in case you are finding the size of a data type instead of a variable.*/
printf("1. size of num : %zu\n", sizeof(int)); 
printf("2. size of num : %zu\n", sizeof(long));
return 0;
}
/* 
OUTPUT :
1. size of int : 4
2. size of long : 8
*/        

  • No Function-Like Behavior: Unlike function, pointer to a sizeof() does not exist, because we know sizeof operator is evaluated at compile time, and it directly returns the size of a type, object, or variable. Since it is not a function, we cannot obtain a pointer to it or pass it as an argument to other functions.

For Example: Note the following piece of code in C:
#include <stdio.h>

void printSize(size_t size) {
   printf("Size: %zu\n", size);
}

int main() {
   int x;
   printSize(sizeof(x)); // Correct: Pass the result of sizeof, which gets evaluated at    compile time, to the function

  /* Incorrect: The following commented line is attempting to get a pointer to sizeof.  This will cause a compilation error, when uncommented */   

  //size_t *ptr = &sizeof(x);  
   return 0;
}        

Availability and Equivalents of sizeof in different languages

The sizeof operator is not available in all programming languages. The presence and behaviour of sizeof also vary in the languages in which it is available. An overview of its availability and equivalents in different languages can be depicted as follows:

  • In C++,? the sizeof operator is inherited from C with the same functionality.
  • As Objective-C is an extension of C, it also has the sizeof operator with the same functionality.
  • In C# , the sizeof operator is also available but is restricted to unsafe contexts for non-primitive types. For examples, refer the following cases:

Case 1 :Using sizeof with primitive types
using System;

class Program
{
    static void Main()
    {
        /* In Safe context,sizeof with primitive types, int, double and char */

        Console.WriteLine("Size of int: {0}", sizeof(int));
        Console.WriteLine("Size of double: {0}", sizeof(double));
        Console.WriteLine("Size of char: {0}", sizeof(char));
    }
}

/* 
OUTPUT:
Size of int: 4
Size of double: 8
Size of char: 2  
*/        


Case 2 : Using sizeof with user-defined structs (requires unsafe context)
using System;

struct MyStruct {
    public int a;
    public double b;
    public char c;
}

class Program {
    static void Main() {
        /* sizeof with user-defined structs (requires unsafe context) */
        unsafe {
            Console.WriteLine("Size of MyStruct: {0}", sizeof(MyStruct));
        }
    }
}

/* 
OUTPUT:
Size of MyStruct: 24 
*/        
Case 3: Using Marshal.SizeOf method for getting size of objects in a safe context
using System;
using System.Runtime.InteropServices;

struct MyStruct {
    public int a;
    public double b;
    public char c;
}

class Program {
    static void Main() {

        /* Marshal.SizeOf for getting size of objects in a safe context */

    Console.WriteLine("Size of MyStruct using Marshal.SizeOf: {0}",    Marshal.SizeOf(typeof(MyStruct)));

/* Using Marshal.SizeOf to get the size of an object instance */

      MyStruct myStructInstance = new MyStruct(); Console.WriteLine("Size of     myStructInstance using Marshal.SizeOf: {0}", Marshal.SizeOf(myStructInstance));
   }
}        
Note:

  1. Marshal.SizeOf is a runtime method that can be used with any type, including managed types and instances of objects.
  2. It does not require an unsafe context.
  3. It calculates the size of the object at runtime, making it more versatile and capable of handling managed objects.

  • In Java, there is no sizeof operator. Java abstracts away the underlying memory management details. However, we can estimate object sizes using libraries like Instrumentation or third-party tools.

  • In Python, there is no sizeof operator. Instead, you can use the sys.getsizeof() function from the sys module to get the size of an object.

the sys.getsizeof() function in Python
import sys

fruitList = ["apple", "banana", "cherry"]
size = sys.getsizeof(fruitList)
print("Size of the list : ",size)        

  • JavaScript neither has a sizeof operator nor its equivalents. Memory management is handled automatically by the JavaScript engine, and there are no built-in tools to directly measure the size of objects.
  • Rust: Rust has a std::mem::size_of function that serves a similar purpose. rust

Case 1:? Using size_of with primitive types
use std::mem;

fn main() {
    // size_of with primitive types
    println!("Size of i32: {} bytes", mem::size_of::<i32>());
    println!("Size of f64: {} bytes", mem::size_of::<f64>());
    println!("Size of char: {} bytes", mem::size_of::<char>());
}

// OUTPUT:
// Size of i32: 4 bytes
// Size of f64: 8 bytes
//Size of char: 4 bytes        
Case 2:? Using size_of with a user-defined struct
use std::mem;

#[derive(Debug)]
struct MyStruct {
    a: i32,
    b: f64,
    c: char,
}

fn main() {
       // size_of with a user-defined struct
      println!("Size of MyStruct: {} bytes", mem::size_of::<MyStruct>());
}

// OUTPUT:

// Size of MyStruct: 16 bytes        
Case 3:? Using size_of_val with an instance of a struct
use std::mem;

#[derive(Debug)]
struct MyStruct {
    a: i32,
    b: f64,
    c: char,
}

fn main() {

    // size_of_val with an instance of a struct
    let my_struct_instance = MyStruct { a: 10, b: 20.0, c: 'A' };

    println!(
        "Size of my_struct_instance: {} bytes", mem::size_of_val(&my_struct_instance)
    ); 

}

/* 
OUTPUT:
Size of my_struct_instance: 16 bytes
*/        
Case 4 :? Using size_of_val with an array
use std::mem;

#[derive(Debug)]
struct MyStruct {
    a: i32,
    b: f64,
    c: char,
}

fn main() {
    // size_of_val with an array
    let array = [1, 2, 3, 4, 5];
    println!("Size of array: {} bytes", mem::size_of_val(&array));
}
/*
OUTPUT:
Size of array: 20 bytes
*/        
Summary Available in C, C++, Objective-C, C# (with restrictions), but not available in Java (no direct equivalent), JavaScript, Python ( uses sys.getsizeof() function ), Rust (uses std::mem::size_of function ), Thus the sizeof operator is primarily a feature of C and C++ and is adapted with some restrictions in C#. Other languages provide alternative ways to measure the size of objects but do not have a direct equivalent to the sizeof operator.

要查看或添加评论,请登录

Arshad Hussain的更多文章

社区洞察

其他会员也浏览了