Thread: same_name permitted

  1. #1
    Registered User
    Join Date
    Apr 2017
    Location
    Iran
    Posts
    138

    same_name permitted

    Hi,

    Why same_name in the following code is permitted ?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    unsigned same_name(void)
    {
        unsigned same_name=0;
        
        return same_name;
    }
    
    int main(void)
    {
        same_name();
    
        return EXIT_SUCCESS;
    }
    same_name is name of a function and it's variable.

  2. #2
    Registered User
    Join Date
    May 2015
    Posts
    56
    Hello,

    The compiler is clever enougth to work out which is a function and which is a variable.
    It is permitted but considered bad practice, it can lead to confusion when the code gets more complex.

    Regards

  3. #3
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    To be more precise, in C scope matters. In cases where you have multiple names in different scopes, the inner-most scope takes precedence. For example, this shouldn't work because the function and the variable are both being declared inside the same exact scope:
    Code:
    #include <stdio.h>
    
    int main(void)
    {
        void name(void);
        int name = 123;
    
        printf("%d\n", name);
        name();
    
        return 0;
    }
    
    void name(void)
    {
        printf("321\n");
    }
    yet this one works just fine:
    Code:
    #include <stdio.h>
    
    int main(void)
    {
        void name(void);
    
        {
        int name = 123;
    
        printf("%d\n", name);
        }
        name();
    
        return 0;
    }
    
    void name(void)
    {
        printf("321\n");
    }
    Devoted my life to programming...

  4. #4
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    To be even more precise, mad-hatter's answer is wrong. It has nothing to do with which is a "variable".
    Explode the sunlight here, gentlemen, and you explode the entire universe. - Plan 9 from Outer Space

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Multicast Problem - Operation Not Permitted
    By CodeBugs in forum Networking/Device Communication
    Replies: 4
    Last Post: 09-02-2010, 11:38 AM

Tags for this Thread