473,795 Members | 3,081 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

max strlen at compile time?



Hi,

can I use the preprocessor, using sizeof(a)/sizeof(a[0]) to yield an
error for too long strings?

Like:

#define CRYPT(a) \
#if sizeof(a)/sizeof(a[0]) 31 \
xCRYPT(a) \
#else\
#error xy\
#endif

(which of course doe not work)
--
-Gernot
int main(int argc, char** argv) {printf
("%silto%c%cf%c gl%ssic%ccom%c" , "ma", 58, 'g', 64, "ba", 46, 10);}

_______________ _______________ __________
Looking for a good game? Do it yourself!
GLBasic - you can do
www.GLBasic.com
Aug 1 '06
14 4552
Gernot Frisch wrote:
>>What we want, then, is a compile-time error if the size of Array
exceeds 31.
Here's how:

char Array[SUSPECT_LENGTH] = {0};
char Error_ArrayIsTo oLong[((sizeof Array / sizeof Array[0] <=
OKAY_LENGTH ) *
2) - 1] = {0};

>>foo.c: In function `main':
foo.c:9: size of array `Error_ArrayIsT ooLong' is negative
foo.c:9: warning: unused variable `Error_ArrayIsT ooLong'

Very clever! Thank you.
Your problem can be generalized to "how to program an elegant and robust
static assert" (compile time assert). Here is what I use (open to any
improvement):

#define cos_STATIC_ASSE RT(cond) \
struct cos_PP_CAT(STAT IC_ASSERT_,__LI NE__) { \
enum { cos_PP_CAT(STAT IC_ASSERT_,__LI NE__) = !(cond) } _; \
int STATIC_ASSERT[(cond) ? 1 : -1]; \
}

where

#define cos_PP_CAT( a,b) cos_PP_CAT_(a,b )
#define cos_PP_CAT_(a,b ) a##b

This should give a meaningfull error message with most compilers.
The enum is there to forbid the use of sizeof at runtime (c99) and to
ensure consistent behavior between c89 and c99.

a+, ld.
Aug 2 '06 #11
One matter I didn't notice at first is that your and Richard's
variants
generate data, while mine doesn't (it just makes a typedef).
That's a point!
Aug 3 '06 #12
Laurent Deniau posted:
int STATIC_ASSERT[(cond) ? 1 : -1];

Would you not prefer a simple typedef?

(COMPASS = Compile-time assert)

Something like:

typedef COMPASS(expr) char[(expr) ? 2 : -2 ];

--

Frederick Gotham
Aug 3 '06 #13
Frederick Gotham <fg*******@SPAM .comwrites:
Laurent Deniau posted:
> int STATIC_ASSERT[(cond) ? 1 : -1];


Would you not prefer a simple typedef?

(COMPASS = Compile-time assert)

Something like:

typedef COMPASS(expr) char[(expr) ? 2 : -2 ];
verify.h from gnulib is a refined version of the idea of a
compile-time assert. I won't post it here, because it's about
150 lines long (mostly comments), but I'd recommend taking a look
at on the web:
http://cvs.savannah.gnu.org/viewcvs/...in&root=gnulib

I found it very educational.
--
"The way I see it, an intelligent person who disagrees with me is
probably the most important person I'll interact with on any given
day."
--Billy Chambless
Aug 3 '06 #14
Frederick Gotham wrote:
Laurent Deniau posted:

> int STATIC_ASSERT[(cond) ? 1 : -1];

Would you not prefer a simple typedef?
why?
(COMPASS = Compile-time assert)

Something like:

typedef COMPASS(expr) char[(expr) ? 2 : -2 ];
This may not detect some problems at compile time but at runtime in c99.

a+, ld.

Aug 4 '06 #15

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

Similar topics

45
11731
by: Matt Parkins | last post by:
Hi, (I realise this probably isn't precisely the right group for this - could someone direct me to the appropriate group to post this question? - thanks !) I'm using Visual C++ 2005 Express Edition Beta (free download from MS - hooray!), and everything works fine, except I get warnings back on the use of some functions, strlen() for example, saying that the function has been deprecated - although they do still work (which is I guess...
12
4428
by: Nollie | last post by:
I need to write a couple of my own string manipulation routines (e.g. a strcpy() alternative that returns the number of chars copied). I've started with one of the simpler functions, strlen(). I've written a very simple version call StringLength(), but it performs significantly slower than its CRT counterparts. Here's my implementation: inline unsigned int StringLength( const char *pszString ) { unsigned int cch = 0;
21
8491
by: sugaray | last post by:
hi, it just came up my mind that since we can get the length of any given string literal S with 'sizeof S-1', so, what's the merit of library function strlen()'s existence ? thanx in advance for your instruction.
81
7358
by: Matt | last post by:
I have 2 questions: 1. strlen returns an unsigned (size_t) quantity. Why is an unsigned value more approprate than a signed value? Why is unsighned value less appropriate? 2. Would there be any advantage in having strcat and strcpy return a pointer to the "end" of the destination string rather than returning a
33
2978
by: apropo | last post by:
what is wrong with this code? someone told me there is a BAD practice with that strlen in the for loop, but i don't get it exactly. Could anyone explain me in plain english,please? char *reverse(char *s) { int i; char *r; if(!s) return NULL;//ERROR r=calloc(strlen(s)+1,sizeof(char));
66
7791
by: roy | last post by:
Hi, I was wondering how strlen is implemented. What if the input string doesn't have a null terminator, namely the '\0'? Thanks a lot Roy
7
2886
by: Duke | last post by:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv) { char *s = "hello strlen"; printf("%s has %d chars.\n", s, strlen(s)); //the above strlen function execute correctly char *msg1 = "abcdefghijklmnopqrstuvwxyz";
53
717
by: ¬a\\/b | last post by:
strlen is wrong because can not report if there is some error e.g. char *a; and "a" point to an array of size=size_t max that has no 0 in it
11
3399
by: Bill Cunningham | last post by:
Strncat is supposed to be better than strcat for some reason I've read. Is this because of a potential buffer overflow? I have compiled properly and used strlen too and I just wonder what is the need to return a strlen? Has anyone used quite abit anyway the strlen function? Bill
0
9672
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
9519
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
10215
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...
0
10001
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
9043
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...
0
6783
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
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4113
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
3
2920
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.