Thread: redinition inside block

  1. #1
    Registered User
    Join Date
    Nov 2012
    Posts
    50

    redinition inside block

    Code:
    #include<stdio.h>
     int i=5;
    main()
    {
        int i=6;
        {
            
            int i=7;
            printf("%d",i);
            
        }
       printf("%d",i);
    }
    Why does the above code doesnot give a variable redifinition error..Although the variable i is defined outside of block also??

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    That's just the way the language was designed.

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    The three i's are in distinct scopes. They are not redefinitions of each other.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    It's not illegal to do such things, but it can lead to occasional confusion.

    Hence this optional warning from GCC
    Code:
    $ gcc -Wall -Wshadow foo.c
    foo.c:3:1: warning: return type defaults to ‘int’ [-Wreturn-type]
    foo.c: In function ‘main’:
    foo.c:5:9: warning: declaration of ‘i’ shadows a global declaration [-Wshadow]
    foo.c:2:6: warning: shadowed declaration is here [-Wshadow]
    foo.c:8:13: warning: declaration of ‘i’ shadows a previous local [-Wshadow]
    foo.c:5:9: warning: shadowed declaration is here [-Wshadow]
    foo.c:13:1: warning: control reaches end of non-void function [-Wreturn-type]
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 04-13-2010, 03:14 PM
  2. Allocate memory inside allocated memory block?
    By Heidi_Nayak in forum C Programming
    Replies: 14
    Last Post: 04-15-2009, 04:19 PM
  3. Making global inside a block
    By siavoshkc in forum C++ Programming
    Replies: 17
    Last Post: 02-07-2006, 08:19 AM
  4. definition inside block
    By PutoAmo in forum C Programming
    Replies: 13
    Last Post: 04-19-2002, 09:20 AM
  5. New Kid on the Block
    By danielthomas3 in forum Game Programming
    Replies: 2
    Last Post: 04-10-2002, 10:36 PM

Tags for this Thread