1

I am trying to access a static variable from other file the following way. Can you please help in printing the value of variable 'c' in file1.c.

Find the code below

File1.c

void main(void)
{
    int m;
    m=func_ret();
    printf("\n m = %d\n",m);
}

File2.c

static int c =5;
int *func_ret(void)
{
    printf("\n c = [%d]\n",c);
    return &c;
}
Madara
  • 163
  • 2
  • 11

2 Answers2

4

The problem here, you're returning a pointer from func_ret() and then, trying to capture the return value in an int variable, then trying to print the value using %d. It mostly invokes undefined behaviour.

For reference, C11, chapter §6.3.2.3

Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behaviour is undefined. The result need not be in the range of values of any integer type.

Solution: You need to change the type of m from an int to int *. You have to use appropriate format specifiers also.

Also note, the recommended signature of main() is int main(void).

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    Even I am trying to figure out why would someone downvote this answer. – WedaPashi Jul 02 '15 at 12:01
  • I didn't down vote, but in most cases conversions from pointer to int are harmless. Worst case scenario is that you will print some garbage value. – Lundin Jul 02 '15 at 13:04
  • 1
    @Lundin sir, I agree with you but at some cases, it can cause problems, right? so, better to use the recommended and defined way, Moreover, I think, in OP's case, it's a matter of oversight. The conversion is not intentional. :-) – Sourav Ghosh Jul 02 '15 at 13:18
  • the capturing of the return value doesnt invoke the undefined behaviour since address is stored in the integer variable. the code snippet in the question works where m prints the address of the variable C, but i wanted the value at C. thanks for the explanation – Madara Jul 03 '15 at 07:10
3

Change your file1.c to:

#include <stdio.h>

extern int *func_ret(void);

int main(void)
{
    int *m = 0;
    m=func_ret();
    printf("\n m = %d\n",*m);
    //some code
    return 0;
}

And file2.c to:

#include <stdio.h>

static int c = 5;
int *func_ret(void)
{
    printf("\n c = [%d]\n",c);
    return &c;
}

Additionally, you should make a habit of using int main(void) instead of void main(). Since that part in not really in scope of this question, instead of writing about it at length, I'll share the link to the related question:
int main(void) vs void main() and,
Why do we need to use int main and not void main in C++?

Community
  • 1
  • 1
WedaPashi
  • 3,561
  • 26
  • 42
  • 1
    Thanks WedaPashi, ur code changes worked, i just had assign the return value to a integer pointer variable in place of integer variable. – Madara Jul 03 '15 at 07:07