I recently came across a golf coding† question in which I thought of writing a function of type int
in main
itself, which could access all variables inside main. But to reduce the number of characters, I thought of writing a function alongside a variable. Something like this :
int i,f(){/*function code*/};
Can I do this? If Yes/No, then why?
† Code Golf is a form of recreational programming in which a given challenge must be solved with the shortest possible program. Reducing the number of characters in the source code is the primary objective, maintainability and readability is unimportant. Please consider this objective before commenting.
The convention in C is has generally been to declare all such local variables at the top of a function; this is different from the convention in C++ or Java, which encourage variables to be declared when they are first used.
Variables belonging to different functions in a single code can have same name if we declare that variable globally as shown in the following code snippet below . Yes, variables belonging to different function can have same name because their scope is limited to the block in which they are defined.
Nested function is not supported by C because we cannot define a function within another function in C. We can declare a function inside a function, but it's not a nested function.
The function declaration creates a variable in the current scope with the identifier equal to the function name.
Like variable in C, we have to declare functions before their first use in program. return_type function_name (type arg1, type arg2 .....); Declaration of a function with multiple input parameter and integer return type.
The syntax for variables declaration is as follows. data_type: Indicates types of data it stores. Data types can be int, float, char, double, long int, etc. variable_name: Indicates the name of the variable. It can be anything other than the keyword. For example, 1, int is a data type, and a is a variable name.
Now, a function name by itself, with no following parentheses, is an expression. The data type of the expression is the type of the function (which includes its return type, the number of parameters it If you give them same name then compiler will confuse that whether you are using variable or function.Hence both are given different names.
There are 5 types of variables which are as follows: 1. Local Variables Variables that are declared inside the functions are called local variable. Local variables must be declared before use. Only local functions can change the value of variables.
int i,f(){/*function code*/};
In C, no you cannot it is not a valid syntax.
What you can do is this:
int i, f(); /* declare an int i and a function f that returns an int */
which is probably not what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With