473,785 Members | 2,819 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sizeof operator implementation

hi,
if you see assembly then sizeof operator has sizeof(type) or
sizeof(variable ) at compile time. How does C compiler gets value at
compiler time.?

How can we implement sizeof operator?

the implementation as macro is as below

#define sizeof_op1(val) (&val +1 ) - &val // for variable ex
sizeof_op1(n)

#define sizeof_op2(type ) ((type*) (10) + 1) - (type*) (10) // for type
as sizeof_op2(int)

is there any other way to implemnent sizeof operator in C ? can we
implemnt sizeof_op2 as function. is there any way to combine above two
macros in one macro or function.

Thanks
vijay

Dec 7 '06 #1
4 17181
vijay wrote:
hi,
if you see assembly then sizeof operator has sizeof(type) or
sizeof(variable ) at compile time. How does C compiler gets value at
compiler time.?
It's the compiler: it does the right sums.
How can we implement sizeof operator?
By being the compiler-writer.
the implementation as macro is as below

#define sizeof_op1(val) (&val +1 ) - &val // for variable ex
sizeof_op1(n)
This is homework, isn't it. Oh well.

When this "works", it will get the answer `1`. It won't work for
things that don't have addresses or, more accurately, things that
aren't legal operands of &.

Conclusion: not useful. And you didn't test it.
#define sizeof_op2(type ) ((type*) (10) + 1) - (type*) (10) // for type
as sizeof_op2(int)
This will /also/ get the answer `1` if it works, and that will
be by coincidence I think, since casting `10` to any pointer type
is at best iffy.

You didn't test this, either.
is there any other way to implemnent sizeof operator in C ? can we
implemnt sizeof_op2 as function.
No.
is there any way to combine above two
macros in one macro or function.
Not if you want a sensible answer.

--
Chris "Perikles triumphant" Dollin
"- born in the lab under strict supervision -", - Magenta, /Genetesis/

Dec 7 '06 #2
"Chris Dollin" <ch**********@h p.comwrote in message
news:el******** **@murdoch.hpl. hp.com...
vijay wrote:
>if you see assembly then sizeof operator has sizeof(type) or
sizeof(variabl e) at compile time. How does C compiler gets value at
compiler time.?
....
>the implementation as macro is as below

#define sizeof_op1(val) (&val +1 ) - &val // for variable ex
sizeof_op1(n )

This is homework, isn't it. Oh well.

When this "works", it will get the answer `1`. It won't work for
things that don't have addresses or, more accurately, things that
aren't legal operands of &.

Conclusion: not useful. And you didn't test it.
Wouldn't this work (for some definition of "work") if you did:

#define sizeof_op1(val) ((char*)(&val+1 )-(char*)(&val))

In fact, I can't see any reason that'd even invoke UB.
>#define sizeof_op2(type ) ((type*) (10) + 1) - (type*) (10) // for
type
as sizeof_op2(int)

This will /also/ get the answer `1` if it works, and that will
be by coincidence I think, since casting `10` to any pointer type
is at best iffy.

You didn't test this, either.
The same trick as above (casting to char* before subtracting) should
"work" for this as well. However, it definitely invokes UB due to
casting 10 to a pointer type; might as well cast 0 and make what you're
doing obvious.

The real answer to this is there's no portable or even unportable way to
implement sizeof() in user code. That's why it's a core language
feature instead of being left to users to roll their own. Users cannot
add _operators_ to C; the problem is that sizeof() doesn't _look_ like
an operator to newbies -- it looks like a function or macro.

The far-simpler offsetof() can at least be implemented non-portably in
user code, but it's still included it in the language definition because
it's needed and there's no portable way to provide it. sizeof() has
much, much bigger problems and there's not even a non-portable way to do
it without specific compiler support -- at which point you might as well
have the compiler implement sizeof() itself.

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking
--
Posted via a free Usenet account from http://www.teranews.com

Dec 7 '06 #3
Stephen Sprunk wrote:
"Chris Dollin" <ch**********@h p.comwrote in message
news:el******** **@murdoch.hpl. hp.com...
>vijay wrote:
>>if you see assembly then sizeof operator has sizeof(type) or
sizeof(variab le) at compile time. How does C compiler gets value at
compiler time.?
...
>>the implementation as macro is as below

#define sizeof_op1(val) (&val +1 ) - &val // for variable ex
sizeof_op1( n)

This is homework, isn't it. Oh well.

When this "works", it will get the answer `1`. It won't work for
things that don't have addresses or, more accurately, things that
aren't legal operands of &.

Conclusion: not useful. And you didn't test it.

Wouldn't this work (for some definition of "work") if you did:

#define sizeof_op1(val) ((char*)(&val+1 )-(char*)(&val))

In fact, I can't see any reason that'd even invoke UB.
Let's ignore the fact that you'd better put parentheses around "val" in the
expansion to avoid some of the sillier pitfalls. Even so, "sizeof_op1(cha r)"
is a syntax error and "sizeof_op1('0' )" a constraint violation. If "f" is
declared as

void f(void);

then "sizeof_op1(&f) " and "sizeof_op1 (f)" are both constraint violations (of
course, so is "sizeof f"). If "a" is declared as

int a[4];

then "sizeof_op1 (a[4])" yields UB.

In C99, an expression not involving sizeof can never return correct results
for variable-sized arrays.

Even if we're very generous and restrict use of the macro to valid objects
of scalar type only, it will still yield UB on objects declared with
register class.

The sizeof operator has none of the above restrictions. But of course, you
did say "some definition of 'work'". So yes, for some definitions, I suppose
it works. But that's not really the point.
>>#define sizeof_op2(type ) ((type*) (10) + 1) - (type*) (10) // for type
as sizeof_op2(int)

This will /also/ get the answer `1` if it works, and that will
be by coincidence I think, since casting `10` to any pointer type
is at best iffy.

You didn't test this, either.

The same trick as above (casting to char* before subtracting) should
"work" for this as well. However, it definitely invokes UB due to
casting 10 to a pointer type; might as well cast 0 and make what you're
doing obvious.
Casting 10 to a pointer type does *not* invoke UB, it invokes
implementation-defined behavior. Conversions of pointers to and from
integers are perfectly legal. What will most likely invoke UB is adding 1 to
the result, since it will probably not point to an object.

However, "casting 0" and then adding 1 to the result will *definitely*
invoke UB, since you're adding to a null pointer, which by definition cannot
point to any object.
The real answer to this is there's no portable or even unportable way to
implement sizeof() in user code. That's why it's a core language
feature instead of being left to users to roll their own.
Indeed. So it's not a good reason to suggest approaches to it anyway. There
be dragons.

S.

Dec 7 '06 #4
Skarmander wrote:
Stephen Sprunk wrote:
"Chris Dollin" <ch**********@h p.comwrote in message
news:el******** **@murdoch.hpl. hp.com...
vijay wrote:
if you see assembly then sizeof operator has sizeof(type) or
sizeof(variabl e) at compile time. How does C compiler gets value at
compiler time.?
...
>the implementation as macro is as below

#define sizeof_op1(val) (&val +1 ) - &val // for variable ex
sizeof_op1(n )

This is homework, isn't it. Oh well.

When this "works", it will get the answer `1`. It won't work for
things that don't have addresses or, more accurately, things that
aren't legal operands of &.

Conclusion: not useful. And you didn't test it.
Wouldn't this work (for some definition of "work") if you did:

#define sizeof_op1(val) ((char*)(&val+1 )-(char*)(&val))

In fact, I can't see any reason that'd even invoke UB.
Let's ignore the fact that you'd better put parentheses around "val" in the
expansion to avoid some of the sillier pitfalls. Even so, "sizeof_op1(cha r)"
is a syntax error and "sizeof_op1('0' )" a constraint violation. If "f" is
declared as

void f(void);

then "sizeof_op1(&f) " and "sizeof_op1 (f)" are both constraint violations (of
course, so is "sizeof f"). If "a" is declared as

int a[4];

then "sizeof_op1 (a[4])" yields UB.

In C99, an expression not involving sizeof can never return correct results
for variable-sized arrays.
Are you saying that

#include <stdio.h>
int main(void) {
int n = 4;
int vla[n];
printf("%td\n", (char *) (&vla + 1) - (char *) (&vla));
}

is not guaranteed to print sizeof(vla)? If so, it is. Arithmetic on
pointers to VLAs behaves the same as ordinary pointer arithmetic.
The same trick as above (casting to char* before subtracting) should
"work" for this as well. However, it definitely invokes UB due to
casting 10 to a pointer type; might as well cast 0 and make what you're
doing obvious.
Casting 10 to a pointer type does *not* invoke UB, it invokes
implementation-defined behavior. Conversions of pointers to and from
integers are perfectly legal. What will most likely invoke UB is adding 1 to
the result, since it will probably not point to an object.
The standard says casting an integer to a pointer type may result in a
trap representation. This is not possible, since merely casting an
integer to a pointer type does not result in an object, and if there is
no object, there is no representation. The intent may or may not be
that simply casting 10 to a pointer type is allowed to result in
undefined behaviour, the standard is not clear. I'd say both Stephen
Sprunk's interpretation and yours are valid.

Dec 8 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
3556
by: Sunil Menon | last post by:
Dear All, A class having no member variables and only a method sizeof(object) will return 1byte in ANSI and two bytes in Unicode. I have the answer for this of how in works in ANSI. But I don't know it returns two bytes in UniCode. Please help... For ANSI: In ISO/ANSI C++ Standard, 5.3.3 § 1, it stays: "The sizeof operator yields the number of bytes in the object representation of its
4
3108
by: Gopal-M | last post by:
I have the problem with sizeof operator I also want to implement a function that can return size of an object. My problem is as follows.. I have a Base class, say Base and there are many class derived from it. At a particular point in my application I need the size of the object pointed to by the base pointer. Eg
2
2469
by: Xiangliang Meng | last post by:
Hi, all. What will we get from sizeof(a class without data members and virtual functions)? For example: class abnormity { public: string name() { return "abnormity"; }
3
2206
by: Christof Warlich | last post by:
Hi, I'm trying to build an _efficient_, _purely_ _abstract_ API for inter process(or) communication, _completely_ hiding any implementation details. The core components are "Buffer", "Address" and "Process". They may be instantiated by a "Factory". Here is a simplified, but compilable version: // Abstract Interface enum OsSelector {
31
2390
by: Anjali M | last post by:
#include <stdio.h> int main() { int number = 10; printf("Number is: %d\n", number); printf("Sizeof of number is: %d\n", sizeof(number++)); printf("Number now is: %d\n", number);
12
7608
by: Anil | last post by:
Hi, Where can I get the source code that has the implementation of the below C operators/functions: malloc sizeof new strcmp strtok
5
2238
by: Aloo | last post by:
dear fellas, this is anupam aka aloo and i have small problem the problem ststes :-- >> IMPLEMENT THE 'sizeof' OPERATOR IN C. i.e find the size of any data without using 'sizeof' operator. >> One soluton is that if the pointer to the data is given then even if we don't know the type we cn just increment the pointer and see by how much it is incremented as the c compiler itself increments it according to its size.
29
2703
by: lnitsu | last post by:
Hello I've got a simple question regarding sizeof operator. why sizeof 'a' return 4? (Note the argument is without parenthesis) If anybody is so kind to answer ... TIA
4
6062
by: Divick | last post by:
Hi, does sizeof operator evaluate the size at compile time or run time ? In other words is sizeof(SomeType) evaluated at compile time or at runtime? Please provide the reasoning involved as well. TIA, Divick
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10324
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10090
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9949
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8971
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6739
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.