doubt regarding return value of a function

F

felix

Hi,

I am not understanding this particular implementation:

/* example.c */
#include <stdio.h>

int gl;

int *fun ( void )
{
return &gl;
}

int main ( void )
{
int n;
*fun()=5; /* is this allowed ? */

n=*fun(); /* Not understanding how this is happening !! */
printf("%d\n",n); /* The value is printed here. Tried on VC compiler
*/

return 0;
}
 
I

Ian Collins

felix said:
Hi,

I am not understanding this particular implementation:

/* example.c */
#include <stdio.h>

int gl;

int *fun ( void )
{
return &gl;
}

int main ( void )
{
int n;
*fun()=5; /* is this allowed ? */
Yes, fun() returns a pointer to int.
n=*fun(); /* Not understanding how this is happening !! */

Dereferencing the fun(), which is a pointer to int.
 
F

felix

*fun()=5; /* is this allowed ? */
Yes, fun() returns a pointer to int.


Dereferencing the fun(), which is a pointer to int.

I am still finding it difficult to understand. Please, can you tell a
bit more about the points that are made ?
 
I

Ian Collins

felix said:
I am still finding it difficult to understand. Please, can you tell a
bit more about the points that are made ?
Consider

int *p = fun()
int n = *p;
 
C

Chris Dollin

felix said:
I am not understanding this particular implementation:

/* example.c */
#include <stdio.h>

int gl;

int *fun ( void )
{
return &gl;
}

`fun` returns a pointer-to-int. Specifically, it returns
a pointer to the variable `gl`.
int main ( void )
{
int n;
*fun()=5; /* is this allowed ? */

Yes. If `E` is an expression of type pointer-to-T, then `*E` is
an lvalue (assignable-to expression [1]) and you can assign to
it if `E` is a legal pointer value. Which it is here, since it's
the address of `gl`.
n=*fun(); /* Not understanding how this is happening !! */

Similarly this gets the value of whatever integer variable [2]
the pointer returned by `fun()` points to.
printf("%d\n",n); /* The value is printed here. Tried on VC compiler
*/

return 0;
}

[1] Ignoring the small print for now.

[2] integer /object/, to be technical.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,539
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top