473,805 Members | 1,998 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

#if sizeof...

Is sizeof() legal within a #if preprocessor line?

Specifically, I would like to use the following "sanity check" at compile
time, but I'm getting an error on the compile about the #if line.

struct foo {
int a;
int b;
};

#if sizeof(struct foo) != 8
#pragma error "sizeof foo is not 8!"
#endif

(Assuming the "#pragma error" generates a compile-time error.)

Yes, I know all about the dangers and non-portability of things like this,
but it's in a low-level TCP/IP communications module, and I'd just like to
add a sanity check at compile time that I'm not on a platform where the
structs don't match the communications protocol.
--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>

Nov 14 '05 #1
18 21817
On Fri, 14 Jan 2005 12:57:56 -0500, Kenneth Brody wrote:
Is sizeof() legal within a #if preprocessor line?
No.
Specifically, I would like to use the following "sanity check" at compile
time, but I'm getting an error on the compile about the #if line.

struct foo {
int a;
int b;
};

#if sizeof(struct foo) != 8
Another problem would be that struct foo doesn't exist during
preprocessing phases.
#pragma error "sizeof foo is not 8!"
#endif

(Assuming the "#pragma error" generates a compile-time error.)

Yes, I know all about the dangers and non-portability of things like
this, but it's in a low-level TCP/IP communications module, and I'd just
like to add a sanity check at compile time that I'm not on a platform
where the structs don't match the communications protocol.


If you're expecting representation to match there are more issues than
just size.

Lawrence

Nov 14 '05 #2
In article <41************ ***@spamcop.net >,
Kenneth Brody <ke******@spamc op.net> wrote:
Is sizeof() legal within a #if preprocessor line?
No. The preprocessor doesn't know about such things.
I'd just like to
add a sanity check at compile time that I'm not on a platform where the
structs don't match the communications protocol.


There are various constructs that you could use to produce
compile-time errors if the size is wrong. For example:

char zzz[1 - 2*(sizeof(struc t foo) != 8)];

But the error message will not be very enlightening.

-- Richard
Nov 14 '05 #3
Richard Tobin <ri*****@cogsci .ed.ac.uk> wrote:
char zzz[1 - 2*(sizeof(struc t foo) != 8)];
A very cute idea! I've stolen it, thank you!

#define CCASSERT(predic ate) _x_CCASSERT_LIN E(predicate, __LINE__)
[...]
#define _x_CCASSERT_LIN E_CAT(predicate , line) \
typedef char constraint_viol ated_on_line_## line[2*((predicate)! =0)-1];

Due to typedef declaration no object is created, and the declaration
requires `predicate' to be a constant (scalar) expression. Another
equivalent possibility would be to replace "typedef" with "extern".
But the error message will not be very enlightening.


The message from gcc is enough informative:
constr.c:30: size of array `constraint_vio lated_on_line_3 0' is negative

--
Stan Tobias
mailx `echo si***@FamOuS.Be dBuG.pAlS.INVALID | sed s/[[:upper:]]//g`
Nov 14 '05 #4
"S.Tobias" wrote:

Richard Tobin <ri*****@cogsci .ed.ac.uk> wrote:
char zzz[1 - 2*(sizeof(struc t foo) != 8)];
A very cute idea! I've stolen it, thank you!


ITYM "snarf". ;-)
#define CCASSERT(predic ate) _x_CCASSERT_LIN E(predicate, __LINE__)
[...]
#define _x_CCASSERT_LIN E_CAT(predicate , line) \
typedef char constraint_viol ated_on_line_## line[2*((predicate)! =0)-1];

Due to typedef declaration no object is created, and the declaration
requires `predicate' to be a constant (scalar) expression. Another
equivalent possibility would be to replace "typedef" with "extern".
But the error message will not be very enlightening.


The message from gcc is enough informative:
constr.c:30: size of array `constraint_vio lated_on_line_3 0' is negative


Nice enhancement.

However, why did you switch "1 - 2*x" to "2*x - 1"?

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>

Nov 14 '05 #5
Lawrence Kirby wrote:

On Fri, 14 Jan 2005 12:57:56 -0500, Kenneth Brody wrote:
Is sizeof() legal within a #if preprocessor line?


No.


That's the conclusion I was coming to. Thanks.

[...]
Yes, I know all about the dangers and non-portability of things like
this, but it's in a low-level TCP/IP communications module, and I'd just
like to add a sanity check at compile time that I'm not on a platform
where the structs don't match the communications protocol.


If you're expecting representation to match there are more issues than
just size.


True. But, as I said, this was just a "sanity check", and "the odds
are" that if the size of the struct matches, the component pieces of
the struct align as expected. Obviously, further testing on a new
platform would be necessary to assure that this was the case.

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>
Nov 14 '05 #6


Kenneth Brody wrote:
Is sizeof() legal within a #if preprocessor line?

Specifically, I would like to use the following "sanity check" at compile
time, but I'm getting an error on the compile about the #if line.

struct foo {
int a;
int b;
};

#if sizeof(struct foo) != 8
#pragma error "sizeof foo is not 8!"
#endif

(Assuming the "#pragma error" generates a compile-time error.)

Yes, I know all about the dangers and non-portability of things like this,
but it's in a low-level TCP/IP communications module, and I'd just like to
add a sanity check at compile time that I'm not on a platform where the
structs don't match the communications protocol.

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>


limits.h has the size of all the variables. You should be able to use something
in there to get the size of int.
Nov 14 '05 #7
Neil Kurzman <ns*@mail.asb.c om> writes:
Kenneth Brody wrote:
Is sizeof() legal within a #if preprocessor line?

Specifically, I would like to use the following "sanity check" at compile
time, but I'm getting an error on the compile about the #if line.

struct foo {
int a;
int b;
};

#if sizeof(struct foo) != 8
#pragma error "sizeof foo is not 8!"
#endif

(Assuming the "#pragma error" generates a compile-time error.)
[...]
limits.h has the size of all the variables. You should be able to
use something in there to get the size of int.


<limits.h> has the bounds of the predefined integer types, not their
sizes. If there are padding bits, you can't reliably determine their
sizes from their bounds.

Also, that doesn't necessarily give you sizeof(struct foo). The
compiler could insert padding between a and b or after b. That's not
likely for a struct with just two int members (sizeof(struct foo) is
almost certainly equal to 2*sizeof(int)), but presumably the OP wants
to do this for more elaborate types.

Note that you can use assert() to force a run-time error. If the
program aborts immediately, that's almost as good as bombing at
compile time.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #8
Kenneth Brody <ke******@spamc op.net> writes:
[...]
#if sizeof(struct foo) != 8
#pragma error "sizeof foo is not 8!"
#endif

(Assuming the "#pragma error" generates a compile-time error.)


Just use "#error" rather than "#pragma error".

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #9
Kenneth Brody wrote on 14/01/05 :
Is sizeof() legal within a #if preprocessor line?


Not portably. A question of stage of translation. At this stage
(preprocessor), the standard says that sizeof is not yet evaluated and
returns 0.

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"Clearly your code does not meet the original spec."
"You are sentenced to 30 lashes with a wet noodle."
-- Jerry Coffin in a.l.c.c++

Nov 14 '05 #10

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

Similar topics

3
3557
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
2
2471
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"; }
19
9238
by: Martin Pohlack | last post by:
Hi, I have a funtion which shall compute the amount for a later malloc. In this function I need the sizes of some struct members without having an instance or pointer of the struct. As "sizeof(int)" is legal I assumed "sizeof(struct x.y)" to be legal too. But is is not: #include <dirent.h>
9
3026
by: M Welinder | last post by:
This doesn't work with any C compiler that I can find. They all report a syntax error: printf ("%d\n", (int)sizeof (char)(char)2); Now the question is "why?" "sizeof" and "(char)" have identical precedence and right-to-left parsing, so why isn't the above equivalent to printf ("%d\n", (int)sizeof ((char)(char)2));
7
1941
by: dam_fool_2003 | last post by:
#include<stdio.h> int main(void) { unsigned int a=20,b=50, c = sizeof b+a; printf("%d\n",c); return 0; } out put: 24
42
2418
by: Christopher C. Stacy | last post by:
Some people say sizeof(type) and other say sizeof(variable). Why?
8
2540
by: junky_fellow | last post by:
Consider the following piece of code: #include <stddef.h> int main (void) { int i, j=1; char c; printf("\nsize =%lu\n", sizeof(i+j));
90
8502
by: pnreddy1976 | last post by:
Hi, How can we write a function, which functionality is similar to sizeof function any one send me source code Reddy
32
2596
by: Abhishek Srivastava | last post by:
Hi, Somebody recently asked me to implement the sizeof operator, i.e. to write a function that accepts a parameter of any type, and without using the sizeof operator, should be able to return the size occupied by that datatype in memory in bytes. Thanks :) Abhishek Srivastava
5
2901
by: Francois Grieu | last post by:
Does this reliably cause a compile-time error when int is not 4 bytes ? enum { int_size_checked = 1/(sizeof(int)==4) }; Any better way to check the value of an expression involving sizeof before runtime ? I also have: { void check_foo_size(void);
0
9716
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9596
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
10356
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
10361
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
6874
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();...
0
5676
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4316
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3839
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3006
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.