Calling function with variable that is being initialized

Viewed 75

I am learning C++ using the books listed here. In particular, I read that using an uninitialized local variable of built in type is undefined behavior. Now, I came across the below given example where the user seems to be using uninitialized variables x and y. The user says:

#include <string>

template<typename T>
T num_convert(const char* s, const T) {
 return static_cast<T>(std::stoll(s));
}

int main() {
//--------------------------v---------------> is this UB because x is uninitialized?
  int x = num_convert("55", x);
//-----------------------------------v------> is this UB because y is uninitialized?
  long y = num_convert("5555555555", y);
}

In the above example, I've used arrows to highlight the points where I have doubts. In particular, I want to know that are the above two highlighted statements UB because x and y are not initialized and the user is passing those to the function by value?

1 Answers

I want to know that are the above two highlighted statements UB because x and y are not initialized and the user is passing those to the function by value?

Yes, your understanding is correct. The variable x and y are uninitialized local variables and they're being used/passed by value when calling the functions. Thus, the program has undefined behavior as x and y have indeterminate values and you're using/copying those values to the parameter of the function.

Related