Thread: Why this code is throwing re-declaration error on using extern?

  1. #1
    Registered User
    Join Date
    Jan 2014
    Posts
    76

    Why this code is throwing re-declaration error on using extern?

    Since any variable can be declared multiple times & this underlying code is allocating memory only once, so why the re-declaration error?

    Code:
    int main(){            //code 1
      externint i;    
      int i =90;
      cout << i << endl;
      return0;
    }
    Code:
    
    extern int i;
    extern int i;
    int main(){    //code 2int i =90; 
    cout << i << endl;
    return0;}
    
    code 2 works fine.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,660
    Because in code 1, you're declaring two different kinds of 'int i' in the same scope.

    In code 2, the extern's are in a different scope.
    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. Allocation error throwing
    By beatleman in forum C++ Programming
    Replies: 1
    Last Post: 03-24-2015, 11:00 PM
  2. Replies: 3
    Last Post: 03-01-2011, 07:00 PM
  3. about extern declaration
    By jam_fiveface in forum C Programming
    Replies: 5
    Last Post: 09-02-2008, 04:45 AM
  4. Fixing incorrect extern declaration
    By cunnus88 in forum C++ Programming
    Replies: 4
    Last Post: 03-30-2007, 03:55 PM

Tags for this Thread