![]() |
| | #1 |
| subminimalist Join Date: Jul 2008 Location: NYC
Posts: 3,946
| test.c:6: warning: initializer element is not constant test.c:6: warning: (near initialization for ‘len’) when i compile this with "len" as a global int (as shown). It doesn't happen if "len" is localized within main(). Code: 1 #include <string.h>
2 #include <stdio.h>
3
4 #define this "that"
5
6 int len = strlen(this);
7 int main () {
8 printf("%d\n", len);
9 }
__________________ Accuracy and integrity mean nothing if you don't make it past the censors...PYTHAGORAS |
| MK27 is offline | |
| | #2 |
| Algorithm Dissector Join Date: Dec 2005 Location: New Zealand
Posts: 2,476
| strlen is evaluated at runtime, not compile-time, as such it must be inside a function. Note that some compilers might be able to optimise it to a compile-time constant, but that doesn't make it valid to assume that you're allowed to do what you're trying to do.
__________________ My homepage Advice: Take only as directed - If symptoms persist, please see your debugger |
| iMalc is offline | |
| | #3 |
| subminimalist Join Date: Jul 2008 Location: NYC
Posts: 3,946
| well i guess that makes sense, since there really is no reason to apply strlen to a global constant anyway -- except sometimes I am lazy about counting...
__________________ Accuracy and integrity mean nothing if you don't make it past the censors...PYTHAGORAS |
| MK27 is offline | |
| | #4 |
| Registered User Join Date: Apr 2006
Posts: 1,193
| You can use sizeof() to get the length of a literal string.
__________________ It is too clear and so it is hard to see. A dunce once searched for fire with a lighted lantern. Had he known what fire was, He could have cooked his rice much sooner. |
| King Mir is offline | |
| | #5 |
| Woof, woof! Join Date: Mar 2007 Location: Australia
Posts: 3,139
| Just be careful, 1. You can't use it on pointers to literals 2. It includes the NUL terminator, ie strlen(x) == sizeof(x) - 1 Not that 1 matters in this case ![]() Code: [zac@neux sandbox]$ gcc -W -Wall -std=c99 -pedantic -O0 sandbox.c -o sandbox
[zac@neux sandbox]$ cat sandbox.c
#include <stdio.h>
#define test "four"
const int len = sizeof(test);
int main(void)
{
printf("%s = %d\n", test, len);
return 0;
}
[zac@neux sandbox]$ ./sandbox
four = 5
|
| zacs7 is offline | |
![]() |
| Tags |
| gcc, warnings |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Exercise asks me to use a subarray. What is a subarray? | yougene | C Programming | 4 | 01-05-2008 11:30 PM |
| Modify an single passed array element | swgh | C Programming | 3 | 08-04-2007 08:58 AM |
| Sorting a 2-dimensional array | kmoyle73 | C++ Programming | 3 | 05-05-2004 01:54 PM |
| Struct *** initialization | Saravanan | C Programming | 20 | 10-09-2003 12:04 PM |
| sorting | penny_731729 | C Programming | 3 | 04-28-2003 10:56 AM |