Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass the result of an assignment to a function in c++?

My question is: "Can I pass the result of an assignment to a function in c++?"

The reason I want to do this is that a variable has a specific type, e.g. "int" so I assign the value to the variable and pass the whole thing to the overloaded function that takes "int" as an argument.

The main reason for doing this is to make the code a bit smaller and easier to read, so instead of:

val = 2
function(val);

I get:

function(val = 2);

Is that ok? If so, is there a convention that says this is poor coding practice for some reason?

Thanks, fodder

like image 516
code_fodder Avatar asked May 01 '13 11:05

code_fodder


People also ask

Can C pass by reference?

Parameters in C functions There are two ways to pass parameters in C: Pass by Value, Pass by Reference.

Can we pass function as a parameter in C?

We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer.

How do you pass a function as a parameter?

Function Call When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this: func(print); would call func , passing the print function to it.

Can a function be a parameter?

A function can take parameters which are just values you supply to the function so that the function can do something utilising those values. These parameters are just like variables except that the values of these variables are defined when we call the function and are not assigned values within the function itself.


1 Answers

Yes

Per paragraph § 5.17 / 1

The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand.

After function(val = 2), 2 assigns to val then the value of val passes to the function.

Talking about readability is not easy, I personally don't use this way in my codes.

like image 183
masoud Avatar answered Sep 25 '22 14:09

masoud