Thread: Taking a value from a function for use in main

  1. #1
    Registered User
    Join Date
    Sep 2018

    Taking a value from a function for use in main

    Trying to get some data found in a function for usage in the int main part of the program. Specifically the size of a section in bytes.
    Tried using external int variable inside and outside of the function, but it was unrecognized when i tried to utilize it in the main.

    int XXX(int XX){
    if(strcmp(name, ".text") == 0){         //If there is a match then print the associated size
         printf("Size of %s = %lu bytes\n", name, shdr.sh_size);
         int Text_Size = shdr.sh_size;
    return 0;
    Last edited by Passwaters; 11-07-2018 at 07:56 PM. Reason: More Info

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    You're allowed to have a bunch of variables with the same name, as long as they have different scope; but you can only see one of them at a time (whichever one is "closest", i.e. has the smallest scope). So the following is perfectly fine:

    int a; //1
    int someFunction(void);
    int main(void) {
        int a;  //2
        if (scanf("%d", &a)) {
            int a = 4;  //3
            printf("a=%d\n", a);
        printf("a also = %d\n", a);
        return 0;
    int someFunction(void) {
        printf("a is %d\n", a); 
            int a = 11; //4
            printf("a is also %d\n", a); 
        return a;
    Each of the variables here has a scope: 1 is in scope for the entire file (and therefore since it has the "largest" scope, it is hidden by any of the other variables named a); 2 is in scope inside main; 3 is in scope inside the if statement; and 4 is in scope only inside those braces in someFunction. You should be able to see then that each printf statement references a different variable "a".

    This is relevant because the line you posted:
    int Text_Size = shdr.sh_size;
    declares a new variable that is only valid inside that if-statement, and doesn't affect any other variable that may have the name Text_Size somewhere else.

    Having said that: I doubt there's a reason why the "normal" returning-a-value-from-a-function mechanism (namely, "return", or if you want an error-code return, passing a pointer to a variable to be filled in by your function) shouldn't be used instead.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 05-08-2014, 10:57 AM
  2. Replies: 3
    Last Post: 06-01-2011, 03:08 AM
  3. Function of mine isn't taking strings right.
    By suzakugaiden in forum C++ Programming
    Replies: 15
    Last Post: 01-30-2006, 07:02 PM
  4. Replies: 4
    Last Post: 01-17-2006, 12:43 PM
  5. taking Function's address
    By arjunajay in forum C++ Programming
    Replies: 2
    Last Post: 09-12-2005, 05:55 AM

Tags for this Thread