G++ "Calling" a Function Without Parenthesis (Not F() But F; ). Why Does It Always Return 1

Why the value of a function is 1?

You're feeding std::cout a funtion pointer to returnvalue instead of calling it, to call it add ():

cout<<returnvalue();

C++ function call without brackets

You can regard clearDisplay as the address of the function. Crucually, it will have a non-zero numerical value, and a statement consisting of a single variable is grammatically correct.

Invoking a function without parentheses

There are several different ways to call a function without parentheses.

Let's assume you have this function defined:

function greet() {
console.log('hello');
}

Then here follow some ways to call greet without parentheses:

1. As Constructor

With new you can invoke a function without parentheses:

new greet; // parentheses are optional in this construct.

From MDN on the new oprator:

Syntax

new constructor[([arguments])]

2. As toString or valueOf Implementation

toString and valueOf are special methods: they get called implicitly when a conversion is necessary:

var obj = {
toString: function() {
return 'hello';
}
}

'' + obj; // concatenation forces cast to string and call to toString.

You could (ab)use this pattern to call greet without parentheses:

'' + { toString: greet };

Or with valueOf:

+{ valueOf: greet };

valueOf and toString are in fact called from the @@toPrimitive method (since ES6), and so you can also implement that method:

+{ [Symbol.toPrimitive]: greet }
"" + { [Symbol.toPrimitive]: greet }

2.b Overriding valueOf in Function Prototype

You could take the previous idea to override the valueOf method on the Function prototype:

Function.prototype.valueOf = function() {
this.call(this);
// Optional improvement: avoid `NaN` issues when used in expressions.
return 0;
};

Once you have done that, you can write:

+greet;

And although there are parentheses involved down the line, the actual triggering invocation has no parentheses. See more about this in the blog "Calling methods in JavaScript, without really calling them"

3. As Generator

You could define a generator function (with *), which returns an iterator. You can call it using the spread syntax or with the for...of syntax.

First we need a generator variant of the original greet function:

function* greet_gen() {
console.log('hello');
}

And then we call it without parentheses by defining the @@iterator method:

[...{ [Symbol.iterator]: greet_gen }];

Normally generators would have a yield keyword somewhere, but it is not needed for the function to get called.

The last statement invokes the function, but that could also be done with destructuring:

[,] = { [Symbol.iterator]: greet_gen };

or a for ... of construct, but it has parentheses of its own:

for ({} of { [Symbol.iterator]: greet_gen });

Note that you can do the above with the original greet function as well, but it will trigger an exception in the process, after greet has been executed (tested on FF and Chrome). You could manage the exception with a try...catch block.

4. As Getter

@jehna1 has a full answer on this, so give him credit. Here is a way to call a function parentheses-less on the global scope, avoiding the deprecated __defineGetter__ method. It uses Object.defineProperty instead.

We need to create a variant of the original greet function for this:

Object.defineProperty(window, 'greet_get', { get: greet });

And then:

greet_get;

Replace window with whatever your global object is.

You could call the original greet function without leaving a trace on the global object like this:

Object.defineProperty({}, 'greet', { get: greet }).greet;

But one could argue we do have parentheses here (although they are not involved in the actual invocation).

5. As Tag Function

Since ES6 you can call a function passing it a template literal with this syntax:

greet``;

See "Tagged Template Literals".

6. As Proxy Handler

Since ES6, you can define a proxy:

var proxy = new Proxy({}, { get: greet } );

And then reading any property value will invoke greet:

proxy._; // even if property not defined, it still triggers greet

There are many variations of this. One more example:

var proxy = new Proxy({}, { has: greet } );

1 in proxy; // triggers greet

7. As instance checker

The instanceof operator executes the @@hasInstance method on the second operand, when defined:

1 instanceof { [Symbol.hasInstance]: greet } // triggers greet

How does the compiler determine what value to output during runtime when a function name is sent to cout without parenthesis? C++

Imagine if the code written is something like

if(returnFive)
returnFive();

Here the expectation is that the compiler checks if the function pointer for returnFive is nullptr or not.

The compiler here is evaluating the function pointer as a boolean expression of whether it is NULL or not and printing the output.

https://godbolt.org/z/Psdc69. You can check that the cout is being passed a (bool).

When to decide to call R functions with bracket vs without bracket

In R you can think of a function as an object. The object has two components: the arguments that the function accepts (called the formals), and the actual code inside the curly brackets called the function body.

For example, lets define a simple function called f:

f <- function(x) { x + 1 }

If we just type f with no parentheses into the console, we can see the formals and body of this new object f:

f
#> function(x) { x + 1 }
#> <bytecode: 0x000001f8dc3e3f50>

We can see its formals separately by doing:

formals(f)
#> $x

And its body by doing:

body(f)
#> {
#> x + 1
#> }

So the function is really just an object. But normally we want to use the function to do some calculation for us. We use a function by calling it. That means that we give some values to the arguments in the formals, and these are used in the calculations inside the body.

When we call a function, we normally do it by putting our variables in parentheses after the function's name:

f(1)
#> [1] 2

But this isn't the only way to call a function. We can give R the function name and the arguments we wish to pass to it in do.call for example:

do.call(f, list(x = 1))
#> [1] 2

We can even build the call as a list of function name and argument, then ask R to evaluate it directly:

eval(as.call(list(f, x = 1)))
#> [1] 2

But the most common way is to simply put parentheses with the arguments after our function name. The R parser recognizes this as meaning "call that function with these arguments". Note that the function doesn't even need a name for this to work:

(function(x){ x + 1 })(1)
#> [1] 2

The reason we sometimes see functions without parentheses after is down to the fact that functions are objects which can themselves be passed to other functions. For example, suppose we have this function:

call_func_with_data <- function(func, data) {
do.call(func, list(data))
}

I can pass any function I want into it and it will try to call it with the data I pass:

z <- 1:10

call_func_with_data(mean, z)
#> [1] 5.5
call_func_with_data(min, z)
#> [1] 1
call_func_with_data(max, z)
#> [1] 10
call_func_with_data(f, z)
#> [1] 2 3 4 5 6 7 8 9 10 11

Note that I have used all these functions without parentheses. This is in essence what is happening inside tidyverse and apply-type functions where you see function names without parentheses after them. It is also what is happening when you use the syntax:

1 %>% f
#> [1] 2

These are just different ways of calling the function.

Created on 2022-01-29 by the reprex package (v2.0.1)

Implement method calling without parentheses

Your problem is a parsing problem. However, the bigger problem is that your language is not syntax-directed. This means that the syntax of your language doesn't match its semantics. For example, consider the following program in your language:

f g

This can be parsed in one of two ways, f applied to g or g applied to f. However, the syntax of the language doesn't make it apparent which one of the two parse trees will be generated. As EJP correctly mentioned, "it is more than a parsing problem, it is a semantic-feedback problem".

So, how to you make your language syntax-directed? Let's take a cue from object-oriented languages. For example:

1 plus 2

In an object-oriented language like JavaScript this might be written as:

Number.prototype.plus = function (n) {

return this + n;

};

var sum = (1) .plus (2);

alert(sum);

Why are parentheses needed on this F# function?

It seems that people coming from C-family languages (C#, Java, C, C++, JavaScript) are having problems understanding the use of brackets in F#. I certainly had, and it took me some years learning how things work.

In a nutshell, the most basic building block in F# is a value. Values can be let-bound:

let foo = bar

This means that foo is a value, which happens to be equal to bar.

Functions are also values:

// 'a -> 'a * 'a
let f = fun x -> x, x

Here, f is a function that takes some value (x) and returns a tuple with x as both the first and the second element.

That's a bit cumbersome to write, so there's a shorthand for that:

// 'a -> 'a * 'a
let f x = x, x

Notice that there are no brackets in these expressions.

Sometimes you need to adjust the precedence of operators. Just like in maths, 1 + 2 * 3 (which is equivalent to 1 + (2 * 3)) isn't the same as (1 + 2) * 3. In F#, you also use brackets to override precedence. Thus

// 'a -> string * 'a
let f x = someOtherFunction x, x

isn't the same as

// x:'a -> string
let f x = someOtherFunction (x, x)

(in this case, someOtherFunction is a function that returns a string.)

Notice that the brackets don't denote a function call; they're only there to control order of evaluation.

Sometimes, you want to define a function that doesn't take any input. You can't, however, define it like this:

let f = whatever

because that would make it a value that's immediately let-bound to whatever. Instead, you can let the function take a value of the built-in type unit. This type only has a single value, which is written ():

let f () = whatever

This means that f is a function that pattern matches its input against the only known value of unit.

Whenever you invoke f with (), the expression whatever is evaluated and returned.



Related Topics



Leave a reply



Submit