Can we declare a function with variables in C?

I recently came across a question about coding golf & dagger; in which I was thinking of writing a function of type int in main , which could access all the variables inside main. But to reduce the number of characters, I was thinking of writing a function next to a variable. Something like that:

 int i,f(){/*function code*/}; 

Can I do it? If yes / no, then why?


& dagger; & emsp; Code Golf is a form of recreational programming in which a given task must be solved using the shortest possible program. Reducing the number of characters in the source code is the main goal, requiring no maintenance or readability. Before commenting, consider this goal.

+5
source share
4 answers
 int i,f(){/*function code*/}; 

In C, no, you cannot be an invalid syntax.

What you can do is:

  int i, f(); /* declare an int i and a function f that returns an int */ 

which is probably not what you want.

+6
source

In C, no function can be defined in another function ... It's just as simple.

As you said, if you want to access the main functional variables in your subfunctions. Its impossible with formal variables. But this can be achieved by calling the link ie using pointer variables

+1
source

In addition to @ouah, I found that you can do this with function pointers. Here is an example:

 int i, (*f)(); f = (int(*)())&i; cout << f << endl; 

the output of this will be address i.

0
source

You can declare a function next to a variable:

 int fgetc(FILE*), getc(FILE*), errno; 

but you cannot define a function next to a variable as production rules for function definitions (see ISO 9899: 2011 ยง6.9.1 ยถ1) read

 function-definition: declaration-specifiers declarator declaration-list(opt) compound-statement declaration-list: declaration declaration-list declaration 
0
source

Source: https://habr.com/ru/post/1236921/


All Articles