Nested function: Difference between revisions

Added GCC specific C implementation.
(Flagged incorrect C++ implementation.)
(Added GCC specific C implementation.)
Line 211:
 
 
=={{header|C}}==
I honestly never thought this task could ever be done in C and then I was surprised, again. It turns out that nested functions although not a C standard are supported by [https://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html GCC]. I used anonymous functions in Java and frankly, I don't see any practical benefit other than making code even harder to read. Then again, that's one of the [http://www.ioccc.org/ strengths of C]. For example, I still have no clue how come the sprintf line is working correctly. I expected the first line of the list to be '1. second', but no, [http://www.netfunny.com/rhf/jokes/90q2/ode.html C is C is C].
'''IMPORTANT'''This implementation will only work with GCC. Go through the link above for details.
<lang C>
/*Abhishek Ghosh, 6th October 2017*/
#include<stdlib.h>
#include<stdio.h>
 
typedef struct{
char str[30];
}item;
 
item* makeList(char* separator){
int counter = 0,i;
item* list = (item*)malloc(3*sizeof(item));
item makeItem(){
item holder;
char names[5][10] = {"first","second","third","fourth","fifth"};
sprintf(holder.str,"%d%s%s",++counter,separator,names[counter]);
return holder;
}
for(i=0;i<3;i++)
list[i] = makeItem();
return list;
}
 
int main()
{
int i;
item* list = makeList(". ");
for(i=0;i<3;i++)
printf("\n%s",list[i].str);
return 0;
}
</lang>
Output:
<pre>
1. first
2. second
3. third
</pre>
=={{header|C++}}==
{{incorrect|C++|This code doesn't compile correctly with a C++11 compatible compiler. Please debug and fix.}}
503

edits