top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

why can we not use function on left side of an expression in C ?

+7 votes
370 views
#include<stdio.h>

int &fun()
{
   static int x;
   return x;
}   

int main()
{
   fun() = 10;
   printf(" %d ", fun());

   return 0;
}

It is fine with c++ compiler while giving error with c compiler.

posted Oct 29, 2013 by Vikas Upadhyay

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+4 votes

In C++ it is a reference so you can assign value to x;

For C you can achieve the same in the following way

int * fun()
{
  static int x;
  return &x;
}

int main()
{
  *(fun()) = 10; 
  printf(" %d ", *(fun()));
}
answer Oct 29, 2013 by Salil Agrawal
Similar Questions
+1 vote

I have written a simple program and stored it with .c file,
When i compiled it with g++ it is getting compiled and giving the proper output when i run that,
but when i compile the same using gcc then it is throwing error.

Below is the sample .c file
#include<stdio.h>
struct A{
        private:
        int a;
        public:
        int sum(){
        a=10;
        }
        void print()
        {
        printf("%d\n",a);
        }
        A()
        {
                printf("Constructor\n");
        }
        A(int b)
        {
                printf("Copy Constructor\n");
        }
        ~A()
        {
                printf("Destructor\n");
        }
};
main()
{
        struct A a(10);
        a.sum();
        a.print();
}
+4 votes

Can someone explain me the usage of function pointer? Probably with real time examples ?

+2 votes

Eg:(())()) - Invalid expression, (()()) - Valid expression?

+4 votes
#include<stdio.h>
int var;
int var;
int var;

int main(void) { 
  printf("%d \n",var); 
  return 0;
}
...