i would like to know the difference between these two in detail.
Thanks
i would like to know the difference between these two in detail.
Thanks
Const just says this variable's value won't change, and so trying to change it will yield a compile error.
Static can mean different things depending on where it's used. If used in a function, it will create a variable which retains its value between function calls. Its lifetime is from the beginning of the program to the end.
On a global level, it has a different meaning, though. I'm sure someone else can fill in on that, but I'd just avoid it. It's not really necessary.
A const is a value which does not change.
You cannot change the value of x without casting it non-const.Code:const int x = 5;
A static variable maintains it's value between function calls:
The first time you call test(), x will be 6. Next time it will be 7, and so on. Ie, because it is static, it is initialized only once during execution (sort of like a global, for which they are useful replacements).Code:void test() { static int x = 5; x++; printf("%d\n",x); }
A static function limits the declaration to file scope:
This will not be accessible to executables which link to the executable compiled from this file*, which can help prevent namespace collisions (at least, I believe that is the purpose). I think this is also the meaning Elysia has in mind WRT to "global" static variables, which would be similarly limited in scope to a single file.Code:static void test();
* or from one file to the next if compiled together
Last edited by MK27; 06-09-2010 at 11:00 AM.
C programming resources:
GNU C Function and Macro Index -- glibc reference manual
The C Book -- nice online learner guide
Current ISO draft standard
CCAN -- new CPAN like open source library repository
3 (different) GNU debugger tutorials: #1 -- #2 -- #3
cpwiki -- our wiki on sourceforge