Can I pass the result of assigning a function to C ++?

My question is: "Can I pass the result of the function assignment in C ++?"

The reason I want to do this is because the variable has a specific type, for example. "int", so I assign a value to a variable and pass it all into an overloaded function that takes "int" as an argument.

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

val = 2 function(val); 

I get:

 function(val = 2); 

This is normal? If so, is there an agreement that says that for some reason this is bad coding?

Thank you feed

+4
source share
3 answers

Yes

In paragraph Β§ 5.17 / 1

Assignment operator (=) and all assignment operators group from right to left. All require modifying the lvalue as their left operand and returning the lvalue related to the left operand.

After function(val = 2) , 2 assigned val , then the value of val goes to the function.

Talking about readability is not easy, I personally do not use this method in my codes.

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

Of course we can do it. the compiler will break this operator function(val = 2) in two steps, which first assign 2 to val , then make a function call with parameter 2. therefore, the first two liner approaches are much cleaner and more readable from the second.

+1
source

C ++ really allows this, but I would not do it if I were you.

Not everything that C ++ allows is a good idea. A good programmer should consider two things: readability and performance. A blogger (I don’t remember who) once said that a programmer does not program computers, they should program for programmers.

This means that you should try to make it as easy as possible. Condensation of several lines into one actually reduces readability, because the reader must stop and think about several things, they need to analyze the concise statement, and not just read it.

What you want to do can also hide errors created by typos. Say for example you typed

 function(val == 2) 

by mistake. The compiler would also allow this, since it will convert bool to int. Another reader will also not understand this error if he / she does not know the parameter list.

If you are interested in tips and tricks and good programming tips, I highly recommend Code Complete 2 . I have had a book for many years and am still learning new things to improve my code.

+1
source

All Articles