CrazyEngineers
  • What is the use of extern keyword in c ?

    Updated: Oct 25, 2024
    Views: 990
    hiiii CEan


    there is compilation error in first program here even out is a global variable but it is not for main

    and in second program out is also declare globally but out put is 100 because of extern so can any one explain me how extern work in this program.

    main()
    {
    printf("%d", out);
    }
    int out=100;
    Answer:
    Compiler error: undefined symbol out in function main.

    and

    main()

    {
    extern out;
    printf("%d", out);
    }
    int out=100;
    Answer:
    100
    0
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • Ankita Katdare

    AdministratorSep 9, 2012

    #-Link-Snipped-#

    In your first program you get a compiler error: undefined symbol out in function main, because according to the syntax a variable is available for use only from the point of declaration. Even though 'out' is a global variable, it is not available for main. Hence an error.

    Whereas in the second program, you get the correct output because the 'extern' keyword extends the visibility of the C variables or functions.

    To understand how external variables relate to the extern keyword, it is necessary to know the difference between defining and declaring a variable.
    When a variable is defined, the compiler allocates memory for that variable and possibly also initializes its contents to some value.
    When a variable is declared, the compiler requires that the variable be defined elsewhere.

    In this case, 'extern' makes sure that the variable 'out' is available in 'main' function.
    Are you sure? This action cannot be undone.
    Cancel
  • optimystix@

    MemberSep 9, 2012

    extern
    Allows one module of your program to access a global variable or function declared in another module of your program.😀
    Are you sure? This action cannot be undone.
    Cancel
  • sulochana anand

    MemberSep 9, 2012

    extern variables are global variables.it can b used across different files.
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register