Autotech Autotech - 2 months ago 4
C++ Question

How is "a" used in my program?

new to learning c++ and I was wanting to understand the program ive practiced. I have a section of code I want to understand but im kind of lost.

#include "stdafx.h";
#include <iostream>;

// getValueFromUser will read a value in from the user, and return it to the caller
int getValueFromUser()
{
std::cout << "Enter an integer: ";
int a;
std::cin >> a;
return a;
}

int main()
{
int x = getValueFromUser(); // first call to getValueFromUser
int y = getValueFromUser(); // second vall to getValueFromUser

std::cout << x << " + " << y << " = " << x + y << std::endl;

return 0;
}


Im just wanting to know how " int a " comes into play here. If someone could help it would be appreciated.

Answer

You declare an uninitialized variable of type int with identifier a:

int a;

The user provides a value to a.

std::cin >> a;

A copy is returned from the function:

return a;

Calls to the getValueFromUser() will create a temporary a,
assign it to user input, and return it each time.

Comments