Thread: Difference between Staic and Const Keywords

  1. #1
    Registered User
    Join Date
    Jun 2010
    Posts
    1

    Difference between Staic and Const Keywords

    i would like to know the difference between these two in detail.
    Thanks

  2. #2
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    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.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    A const is a value which does not change.
    Code:
    const int x = 5;
    You cannot change the value of x without casting it non-const.

    A static variable maintains it's value between function calls:
    Code:
    void test() {
         static int x = 5;
         x++;
         printf("%d\n",x);
    }
    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).

    A static function limits the declaration to file scope:
    Code:
    static void test();
    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.

    * 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

Popular pages Recent additions subscribe to a feed