Not long started c++, and I thought I had a handle on it, but I ordered this book called c++ without fear, and since I have started reading it I am becoming more and more confused. I am on the chapter using functions and the examples in the book firstly should mirror the examples on the internet, but they dont, and now unless I am reading this coded wrong, it has me confused. I will put comments in could please someone explain, as I think the code is wrong: Code: #include <iostream> #include <math.h> using namespace std; int prime(int n); int main() { int i;[COLOR="SeaGreen"] int being declared here as i[/COLOR] while (1) { cout << "Enter a number (0 to exit) and press ENTER: "; cin >> i; [COLOR="SeaGreen"]User input now defined as i[/COLOR] if (i == 0) break; if (prime(i)) cout << i << " is prime" << endl; else cout << i << " is not prime" << endl; } cout << endl; system("PAUSE"); return 0; } int prime(int n) { int i;[COLOR="SeaGreen"] Int i now declared a 2nd time[/COLOR] double sqrt_n = sqrt(static_cast<double>(n)); for (i = 2; i <= sqrt_n); i++) [COLOR="SeaGreen"]Int i now defined a 2nd time as 2[/COLOR] { if (n % i == 0) return false; } return true; } Now as I has been declared and defined in main, how can you redeclare and define it in the function as a different variable, surely they would need to be 2 separate declarations and definitions, for example, use int n in the main, and int i in the function Am I wrong in what I am saying? I have put my comments in green
This is an exercise where the user has to input a number, and the program has to return if it is a prime number or not. The code is using a function as declared before int main, and defined after int main. Now in int main, the users input has been assigned int i as the value. In the function it tests the number by using the square root in c maths. for (i = 2; i <= sqrt_n); i++) { if (n % i == 0) } My question is, that the code is using int n as the users input, but in main it has been assigned int i, this is where I am getting confused
Okay finally got it. int i stores the users input, and when the function is called, the value in int i in main, is copied into int n in the function (the argument). The copying of argument (int i in main) value to parameter (int n function), is called passing by value
It's misleading to state that i has been declared a second time. Local variables are local to a function and have no global effect. The i local to main has been declared once and once only, and the i local to prime has been declared once and once only. There is no clash between identical variable names in different functions. So they already ARE two separate definitions and declarations. There is no link between main's i and prime's i.
yeah its something known as scope the scope of the variable is the scope of the function for example if you declare i in one function you can not access the value of i outside the function there is a lot in scope..........