Thread: Where can & can't variables be declared in C?

  1. #1
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545

    Where can & can't variables be declared in C?

    Hi,
    This is probably a simple question for most of you, but I was just wondering about the rules regarding where variables (inside functions) can be declared?

    I always thought they could only be declared at the top of a function before any real code, but I've seen variables declared further down in some C code (like inside loops...).

    Also, do different versions of C (like C99...) support putting variable declarations in different spots?

    And one other thing... what about variable initialization rules? Can any variable be initialized when it's declared (assuming other declarations follow it), or just ints?

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    In "standard C" (rather than C++) you can declare variables at the beginning of a block in a function, so essentially anywhere between a { and the first line of "actual code".

    So:
    Code:
    int main()
    {
        // Here
        some_code();
        // Note here. 
        { 
            /// Here
            some_function();
            // Not here
           switch(a)
           {
              case 1: // Not here. 
                   break;
              case 2:
                   { // Here 
                      x = 9;
                      // not here. 
                   }
                   break;
               case 3:
                    if (x == 9) {
                         int y = 43;
                         z = 11;
                         if (b)  // Not here. 
                         else {
                           // Here 
                         }
                      }
                      break;
            }
            // Artificial block for a variable 
            {
                int somevar;
                .... 
            }
    }
    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Devil™
    Join Date
    Oct 2007
    Location
    IIT-Kharagpur, India
    Posts
    104
    Quote Originally Posted by matsp View Post
    In "standard C" (rather than C++) you can declare variables at the beginning of a block in a function, so essentially anywhere between a { and the first line of "actual code".

    So:
    Code:
    int main()
    {
        // Here
        some_code();
        // Note here. 
        ...
    }
    --
    Mats
    I think in C99 one can do this.. it works for me.. long ago I tdidnt..
    I am using GCC 4.1 on Linux
    C's Motto: who cares what it means? I just compile it!!

  4. #4
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Thanks. I had a feeling it was something like that.
    I'd rather not use C99 features just yet, since some widely used compiler$ still don't support it.

    Any thoughts about what/when variables can be initialized during declaration?

  5. #5
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by cpjust View Post
    Thanks. I had a feeling it was something like that.
    I'd rather not use C99 features just yet, since some widely used compiler$ still don't support it.

    Any thoughts about what/when variables can be initialized during declaration?
    All variabels should be able to be initalized whenever they are declared. You can't call functions to initialize global variables in "C".

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  6. #6
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Code:
           switch(a)
           {
              case 1: // Not here. 
                   break;
    Actually, you can declare a variable in that particular place (at least according to Dinkumware), because it's the first case statement in the switch. But we know what you mean -- in general, a case statement doesn't constitute the beginning of a block, so you normally can't declare anything there.

    Code:
                         if (b)  // Not here.
    Why not?
    Code:
    if(b) int x;
    Of course, that wouldn't be very useful, because you couldn't use x at all . . .

    To state this slightly more formally: variable declarations must be the first code inside a block. A block is enclosed with {}, and also occurs when you put only one statement after an if or else clause, or a loop.
    Code:
    if(1) int x;
    do
        int x;
    while(0);
    while(1) int x;
    Of course, that's rarely (if ever) useful.

    One point that should be clarified is that a switch statement's block begins at the {, not at each individual case label.

    Also note that any code other than a declaration will end the "beginning" of the block and make it impossible to declare a variable. These are all declarations, and thus can be intermingled with variables:
    Code:
    void function(void);
    typedef int number;
    struct whatever {};
    enum { MAX = BUFSIZ };
    int x = y;
    int x = yes();
    double f = pow(2, 8);
    These are not declarations, they are statements:
    Code:
    x = 0;
    if(x) {}
    x = y;
    x = yes();
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  2. Craps Program with Local Variables
    By tigrfire in forum C Programming
    Replies: 12
    Last Post: 11-09-2005, 09:01 AM
  3. why automatic variables are assigned with garbage values
    By srinivasg in forum C Programming
    Replies: 1
    Last Post: 11-08-2005, 07:14 AM
  4. Question about Static variables and functions.
    By RealityFusion in forum C++ Programming
    Replies: 2
    Last Post: 10-14-2005, 02:31 PM
  5. functions to return 2 variables?
    By tim in forum C Programming
    Replies: 5
    Last Post: 02-18-2002, 02:39 PM