tags:

views:

46

answers:

2

Hello,

I have a C-program (an Apache module, i.e. the program runs often), which is going to write() a 0-terminated string over a socket, so I need to know its length.

The string is #defined as:

#define POLICY "<?xml version=\"1.0\"?>\n" \
   "<!DOCTYPE cross-domain-policy SYSTEM\n" \
   "\"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd\"&gt;\n" \
   "<cross-domain-policy>\n" \
   "<allow-access-from domain=\"*\" to-ports=\"8080\"/>\n" \
   "</cross-domain-policy>\0"

Is there please a way, better than using 1+strlen(POLICY) at the runtime (i.e. calculating that length again and again)?

Some preprocessor directive which would allow me to set POLICY_LENGTH already at compile time?

Thanks, Alex

+2  A: 

Use sizeof(). e.g. sizeof("blah") will evaluate to 5 at compile-time (5, not 4, because the string literal always includes an implicit null-termination character).

Oli Charlesworth
You might want to make sure it's clear why it evaluates to 5 and not 4.
R..
+1  A: 

sizeof works at compile time

#define POLICY "<?xml version=\"1.0\"?>\n" \
   "<!DOCTYPE cross-domain-policy SYSTEM\n" \
   "\"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd\"&gt;\n" \
   "<cross-domain-policy>\n" \
   "<allow-access-from domain=\"*\" to-ports=\"8080\"/>\n" \
   "</cross-domain-policy>\0"

char pol[sizeof POLICY];
strcpy(pol, POLICY); /* safe, with an extra char to boot */

If you need a pre-processor symbol with the size, just count the characters and write the symbol yourself :-)

#define POLICY_LENGTH 78 /* just made that number up! */
pmg
or `#define POLICY_LENGTH (sizeof(POLICY))`...
Oli Charlesworth
@Oli: I'm guessing pmg meant an expression valid for use in preprocessor conditionals, which `sizeof` is not..
R..
@R: I didn't know that. That could potentially be quite annoying...
Oli Charlesworth