- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement your own sizeof operator using C++
There is an option that we can implement our own sizeof() operator. The operator sizeof() is a unary operator and is used to calculate the size of any type of data. We can use #define directive to implement our own sizeof() operator which will work exactly same as sizeof() operator.
Here is the syntax to implement own sizeof() operator,
#define Any_name(object) (char *)(&object+1) - (char *)(&object)
Here,
Any_name − The name you want to give to your own sizeof() operator.
Here is an example to implement sizeof() operator in C language,
Example
#include <stdio.h> #define to_find_size(object) (char *)(&object+1) - (char *)(&object) int main() { int x; char a[50]; printf("Integer size : %d\n", to_find_size(x)); printf("Character size : %d\n", to_find_size(a)); return 0; }
Output
Integer size : 4 Character size : 50
In the above program, #define directive is used to declare our own sizeof() operator and it is calculating the size of integer and character type array.
#define to_find_size(object) (char *)(&object+1) - (char *)(&object) …. int x; char a[50]; printf("Integer size : %d\n", to_find_size(x)); printf("Character size : %d\n", to_find_size(a));
Advertisements