1

I am trying to write code with expression templates that will permit me to perform operations on objects of different types, and I am trying to customize that behavior. For this purpose, it would be convenient for me if I could write a function such as:

double ReturnVal() {};

This code produces a compiler warning "no return statement in function returning non-void". But - the function appears to do what I want. Specifically, if I run:

double x = 5;
x = ReturnVal();

I find that x remains 5. It is unchanged by the function ReturnVal(). This is what I want the code to do.

I know this seems odd, but again, this would be useful because I am trying to write code with templates, and customizing the behavior of operators when they operate on similar (but different) types objects.

So, the question is - can I rely on this behavior that "x = ReturnVal()" doesn't change x? That's what I want, and it's what I am seeing gcc do in my testing. But I am nervous that this may be undefined behavior, and I can't rely on it.

pah52
  • 85
  • 6
  • 2
    You can't rely on this. It is Undefined Behavior. http://eel.is/c++draft/stmt.return#4 – François Andrieux Jun 15 '21 at 14:57
  • You may see that behavior in this particular case - but it may do something completely bonkers in another place - even within the same program. – Ted Lyngmo Jun 15 '21 at 15:00
  • Thanks. That's a pity. Would have been useful. – pah52 Jun 15 '21 at 15:02
  • Why not `void ModifyVal(double&) {}`? – Jarod42 Jun 15 '21 at 15:02
  • @Jarod42 Yes, that's probably what I'll do. Typically, for basic data types like a double, I try to pass and return by value if feasible (instead of pass/return by reference), because it can be more readable code and possibly more efficient. But in this case, I may have no choice but to pass by reference. My function will be run many many times, so performance does matter in my case. – pah52 Jun 15 '21 at 15:09
  • `double ReturnVal(double d) { return d; }`, and `x = ReturnVal(x);` if really you want to return by value... – Jarod42 Jun 15 '21 at 15:16
  • Yeah, that's an interesting idea. I am dealing with templates, so implementing the same methods in multiple classes. So sometimes, I am using ReturnVal to actually return a value from an object. So in those contexts, it'd lead to an odd style where I'd have something like x = ReturnVal(x). And then in that case, the function would be: double ReturnVal(double x) { return val};, and it would not be using the input argument x. I'm not sure which would lead to more efficiently running code - doing that or using the pass by reference. – pah52 Jun 15 '21 at 15:21

0 Answers0