Can we use function on left side of an expression in C and C++?

 

  In C, it might not be possible to have function names on left side of an expression, but it’s possible in C++.

 1 #include<iostream>
 2 using namespace std;
 3 
 4 /* such a function will not be safe if x is non static variable of it */
 5 int &fun()
 6 {
 7     static int x; 
 8     return x;
 9 }    
10 
11 int main()
12 {
13     fun() = 10;
14     
15     /* this line prints 10 on screen */
16     printf(" %d ", fun());
17     
18     getchar();
19     return 0;
20 }

 

  不过,貌似C语言中也是可以的,比如下面的例子。

 1 #include<stdio.h>
 2 int* fun()
 3 {
 4     static int x;
 5     return &x;
 6 }
 7 
 8 int main()
 9 {
10     *(fun()) = 10; 
11     /* this line prints 10 on screen */
12     printf(" %d ", *(fun()));
13     return 0;
14 }

 

 

  

  Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


  转载请注明:http://www.cnblogs.com/iloveyouforever/

  2013-11-27  12:23:57

posted @ 2013-11-27 12:24  虔诚的学习者  阅读(168)  评论(0编辑  收藏  举报