I am trying to create a integer variable in a if statement body like this:
if (a == 72){
cout <<"You Are CORRECT1"<<endl;
int aa = 1;
}
else{
cout <<"No. The answer is "<<12*6<<endl;
int aa = 2;
}
When I compile this it says:
42 C:\Documents and Settings\Valued Customer\Desktop\C++\Variable.cpp aa undeclared (first use this function)
Could you please help me.
Declare the variable before like so.
int aa;
if (a == 72)
{
cout <<"You Are CORRECT1"<<endl;
aa = 1;
}
else{
cout <<"No. The answer is "<<12*6<<endl;
aa = 2;
}
Your variable declaration is correct, the problem ís that the lifetime of your variable is only valid inside the block in which it was declared. Any attempts to use it outside this block is invalid.
You can use the conditional operator for this kind of situation:
int aa = a == 72 ? 1 : 2;
This allows you to initialize a variable based on a condition, something which cannot be done with an if-else statement. You will have to deal with writing to stdout separately though.
It's likely telling you this when you're outside of your if/else statement. In the example you give, you're creating local variables inside the scope of the if and the else. They go out of scope and "cease to exist" after the if / else stuff.
Here's the way you should do it:
int aa = -1;
if (a = 72)
{
cout << "You are CORRECT1" << endl;
aa = 1;
}
else
{
cout << "No. The answer is " << 12 * 6 << endl;
aa = 2;
}
cout << aa << endl;
By doing it this way, you declare the int outside of the scope of the if/else code block, so the variable continues to survive, and can be accessed outside of that code block.
Related
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int b = 2;
if(a > 0)
{
cout << "we are in the first" << endl;
if(b > 3)
{
cout << "we are in the second" << endl;
}
}
else
{
cout << "we are in else" << endl;
}
}
According to the C++ISO:
In the second form of if statement (the one including else), if the
first substatement is also an if statement then that inner if
statement shall contain an else part. In other words, the else
is associated with the nearest un-elsed if.
I thought that my code above would print out "we are in else", since the condition of the nearest un-elsed if, the inner one, resulted in false. What did I miss?
The standard talks here about no block statements. In situation like this:
if (a > 0)
if (b > 3) std::cout << "nested-if\n";
else std::cout << "nested-else\n";
else is a part of the nested if. Such things must be unambiguous in standard, but I strongly recommend using block statements (wrapped in {}) in every situation to prevent confusion.
When they say "nearest" then they refer to the distance to the whole if statement, not only the if keyword. The whole if statement is:
if (a>0){
cout<<"we are in the first"<<endl;
if (b>3){cout<<"we are in the second"<<endl;}
}
It ends at the }. The } closes the block of the outer if and that is the if which is closes to the else.
See also here for a little more formal explanation of the if-statement consisting of more than just the if: https://en.cppreference.com/w/cpp/language/if.
Context. The part you're missing is context.
Every time you open a {} pair you introduce a new context, so the exterior else only "knows" about the first if.
The if inside the new context could have an else of it's own. If you wanted the behavior of the else being pertaining to the last if, you should not have created a new context.
E.g:
if (someVar == true)
if (someOtherVar == true)
cout << "Some text" << endl;
else
cout << "Some other text" << endl;
else
cout << "Another entirely different text" << endl;
Your code -
int a =1;
int b =2;
if (a>0)
{
cout<<"we are in the first"<<endl;
if (b>3){cout<<"we are in the second"<<endl;}
}
else
{
cout<<"we are in else"<<endl;
}
Logic path -
int a =1;
int b =2;
if (1>0)
{
cout<<"we are in the first"<<endl;
if (b>3){cout<<"we are in the second"<<endl;}
}
else
{
cout<<"we are in else"<<endl;
}
int a =1;
int b =2;
cout<<"we are in the first"<<endl;
if (b>3){cout<<"we are in the second"<<endl;}
we are in else is not executed.
I am making a finite state machine for a coding class. How can I use the return value to change the value of int HP in my main so I will not have any other problems with my code. I just want to make it able to manipulate the value of HP, and use the new value of HP for more functions.
Sorry if the fix to this problem is really simple. I am struggling to understand how functions work in C++ and cannot seem to find a solution any other place online or reading tutorials.
#include <iostream>
#include <time.h>
using namespace std;
int forage(int HP) {
cout << "The ant is in foraging state."<<endl;
if (rand() % 100 < 60) {
cout << "The ant found something!"<<endl;
if (rand() % 100 < 10) {
cout << "The ant found poison!" << endl;
HP -= 1;
}
else {
cout << "The ant found food!" << endl;
HP += 1;
}
}
int mHP = HP;
return mHP;
}
int main() {
srand(time(NULL));
int mHP = 0;
cout << "Welcome to Ant Simulator"<<endl;
forage(10);
cout << mHP;
system("pause");
return 0;
}
You have a couple of choices. One possibility is to pass HP by reference, and have forage modify what was passed in:
void forage(int &HP) {
cout << "The ant is in foraging state."<<endl;
if (rand() % 100 < 60) {
cout << "The ant found something!"<<endl;
if (rand() % 100 < 10) {
cout << "The ant found poison!" << endl;
HP -= 1;
}
else {
cout << "The ant found food!" << endl;
HP += 1;
}
}
}
Another possibility is to just use the result returned from forage:
mHP = forage(10);
If you're going to do this, you can add an annotation so that a recent compiler will tell you about the problem if you accidentally ignore the value it returned:
[[nodiscard]] int forage(int HP) {
// ...
The [[nodiscard]] tells the compiler you want to be sure the value returned from this function isn't discarded like your code in the question did.
As an aside, I'd also prefer that forage be separated into a couple of separate pieces. I'd prefer to have one piece that deal strictly with the UI (displaying the strings about what happened) and another that deals strictly with the logic of the game itself. As a starting point, you might consider passing a stream as a parameter, and having forage display to that stream:
void forage(int &HP, std::ostream &s) {
s << "The ant is in foraging state.";
if (rand() % 100 < 60) {
s << "The ant found something!\n";
if (rand() % 100 < 10) {
s << "The ant found poison!\n";
HP -= 1;
}
else {
s << "The ant found food!\n";
HP += 1;
}
}
}
This can help with things like porting the game to work under a windowing system, if you ever decide to do something like that.
Change forage(10); to mHP = forage(10);
Your function forage is of return type int. If you want to get this return value into your variable mHP, you need to assign the return value of the function to the variable as described above.
Just to add to the previous answers... For a basic understanding how a function works with your defined function as an example:
int forage(int HP){...}
The int prior to the function name defines the return type, so basically what your function is giving back at the end of execution.
Then comes the name of your function, in this case forage, followed by the input parameters. In your case there is only one single input parameter which is an integer value int HP. All the code inside of the curly brackets is executed at function call.
Now all functions that do not have the return type void have a return statement somewhere (most of the times at the end) in their code. The actual return value is assigned to a variable like this:
int returnedValue;
receivedValue = forage(10);
I am learning c++ and I came across a really odd phenomenon in a program. I haven't seen any documentation on this problem. Why is that when I initialize a variable inside of a conditional statement it isn't recognized outside of it? Is the variable local to the conditional statement?
Here is an example:
#include "stdafx.h"
#include <iostream>
using namespace std;
/*scope / range of variables */
int global;
int main()
{
int local = rand();
cout << "value of global " << global << endl;
cout << "value of local " << local << endl;
int test = 10;
if (test == 0)
{
int result = test * 10;
}
cout << "result :" << result << endl;
return 0;
}
In this case result is undefined. Can someone please explain what is going on?
As pointed out in the comments, your declaration of result is local inside the if() blocks scope you provided:
if (test == 0)
{ // Defines visibility of any declarations made inside
int result = test * 10;
} // ^^^^^^
Hence the statement
cout << "result :" << result << endl;
would lead to a compiler error, since result isn't visible for the compiler at this point outside that scope.
But even if you declare result correctly outside of the scope block, your logic
int result = 0; // Presumed for correctness
int test = 10;
if (test == 0)
{
result = test * 10; // Note the removed declaration
}
doesn't make much sense, since test was given the value 10 immediately before testing it against the value 0 in your your if() statements condition, and the condition never would become true.
While studying the C++ programming language by B. Stroustrup, it has been mentioned the existence of the prim() functions which reduces the scope of the declared variable to one single block.
This is an example provided by the book:
if (double d = prim(true)) {
left /= d; break;
}
Despite understanding its interest, I cannot figure out how to use it: is it part of a certain library ? Of must I precise the standard because Visual Studio isn't able to recognise the function.
Thanks in advance
The code demonstrates an ability to declare a local variable inside a header of an if statement. It has nothing to do with prim(...) function, which is probably defined in some other place in the book.
Here is another example:
int k = 3;
if (int d = k*50) {
cout << "hello " << d << endl;
}
This prints hello 150. Variable d is accessible only inside the body of the if statement.
Note that the scope of d extends to else branch as well (demo):
int k = 0;
if (int d = k*50) {
cout << "hello " << d << endl;
} else {
cout << "goodbye " << d << endl;
}
Note: In the example above there is no reason to check d in the else branch because it is guaranteed to be zero.
There is no prim() function in the standard library. It is a user defined function used to demonstrate that the condition in the if statement can be a declaration. The function itself is defined in Section 10.2.1 on page no. 245.
In the following program:
#include <iostream>
using namespace std;
int main(){
int i = 99;
for(int i = 1; i <= 10; i++)
{
cout << i << endl;
}
cout << endl << endl;
cout << i << endl;
return 0;
}
I am not getting an error on compilation.
My question is why this is happening.
The int variable i was declared twice. The first time i was declared in the main() function and thus its scope will be this whole main() function including the for loop. The second time i was declared with the for loop and thus its scope will be only the for loop. So, now inside the scope of the for loop there exists two int variablesi. Shouldn't this be a cause of error? And if not why?
Second thing is the output I am getting:
1
2
3
4
5
6
7
8
9
10
99
I also don't understand the output. Why after the execution of the for loop, the value of i that is being printed is 99 and not 10.
You can define variables with the same names in different scopes. The first variable i is defined in the scope of the main function. In the loop there is another implied nested and anonymous scope for the variables you declare for the loop.
For the compiler, the code
for(int i = 1; i <= 10; i++)
{
cout << i << endl;
}
is more or less equivalent to
{
int i;
for(i = 1; i <= 10; i++)
{
cout << i << endl;
}
}