Hi,
can you have a quick look at the two for loops here. I've declared the int 'i' in the first for loop but in the second for loop it doesn't recognise it and i have to declare it again. Why is that?

for(int i=0; i<x; i++)
	  {
		  cout << "Enter a number ";
		  cin >> y;
		  *(aaa + i)= y;
	  }
  }

  cout << "The numbers entered are ";
  for(int i=0; i<x; i++)
	   cout << *(aaa + i) << ", ";

Dani AI

Generated

The second loop can't "see" i because the declaration for (int i = …) creates a name whose scope is limited to that single for-statement (its init, condition, increment and body). As and noted, older compilers sometimes left loop counters visible outside the loop, but standard C++ confines the counter to the loop — think of 's "room" analogy: the loop is a room and i stays in that room.

Two simple ways to fix it: declare a loop counter in each loop (typical and preferable), or declare a counter in an outer scope if the same variable must persist after the loop. Better modern practice is to avoid manual new/raw pointers and use a container so scope and lifetime are automatic. Example using std::vector plus a robust pause at the end:

#include <iostream>
#include <vector>
#include <limits>

std::size_t n;
if (!(std::cin >> n)) return 0;
std::vector<int> v(n);
for (std::size_t i = 0; i < n; ++i) std::cin >> v[i];

for (auto val : v) std::cout << val << ", ";

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.get();

A few practical tips: follow ’s advice and always use braces for clarity; compile with warnings enabled (e.g. -Wall -Wextra) so undeclared names and other problems are flagged; prefer std::vector or smart pointers instead of raw new[] (and if new must be used, remember delete[]). For pausing after formatted input use std::cin.ignore(...); std::cin.get(); to consume the leftover newline.

Recommended Answers

All 8 Replies

Always use { } to make your code readable and consistent.
This then no longer will be a problem.

ok , i did that, but it's still doesn't recognise 'i' in the second for loop. Here's the full program. (Yeah i know i shouldn't be using _getch(), i'll get around to sorting that out.)

#include <iostream>
#include <sstream>
#include <fstream>
#include "conio.h"
using namespace std;

int main()
{
  int x, y;
  int * aaa;
  
  cout << "How many numbers do you want to enter? \n";
  cin >> x;

  aaa = new(nothrow) int[x];

  if (aaa==0)
	  cout << "Error, memory not assigned";
  else
  {
	  for(int i=0; i<x; i++)
	  {
		  cout << "Enter a number ";
		  cin >> y;
		  *(aaa + i)= y;
	  }
  }

  cout << "The numbers entered are ";

  for(i=0; i<x; i++)  
  {
	    cout << *(aaa + i) << ", ";
  }


  _getch();
}

ok , i did that, but it's still doesn't recognise 'i' in the second for loop.

That's because you didn't define it in the second loop. You only defined i in the first loop.

(Yeah i know i shouldn't be using _getch(), i'll get around to sorting that out.)

Why "get around" to it? Just use cin.get() and be done with it...

because when i use cin.get() the command prompt closes before i press a key

That's because you read the number from your input but not the NewLine you also pressed. Loop up cin.ignore ...

I'm surprised the _getch didn't do the same thing...

Like Walt P says, when you define an integer within a for loop, it only is recognized within that for loop in which it is defined. If you would have defined i outside of the for loop, then your code will work.

Think of a function as a building,

You can walk down the hall all the way, and when you get to a room the door/walls etc belong to that room, (room = loop, if, case, etc)

You cant access the door from the next or the previous room in the room you currently are (now don't get technical and create doors from 1 room to the other :P, this example there is only a hallway and the rooms branch from that) ;)

Hi,
can you have a quick look at the two for loops here. I've declared the int 'i' in the first for loop but in the second for loop it doesn't recognise it and i have to declare it again. Why is that?

for(int i=0; i<x; i++)
	  {
		  cout << "Enter a number ";
		  cin >> y;
		  *(aaa + i)= y;
	  }
  }

  cout << "The numbers entered are ";
  for(int i=0; i<x; i++)
	   cout << *(aaa + i) << ", ";

You can also look at it this way:
What happens in Vegas stays in Vegas. Your for loop is Vegas.

Actually, it has to do with variable scope. If you have code like this:

int main()
{
   .....
   .....
 
  {
      int x = 7;
      cout << x;    //no problem
  }

   cout << x;      // ERROR - x undeclared indentifier.

   return 0;
}

Any variable defined within brackets { } is not visible, and in most cases doesn't even exist anymore, outside of those brackets. And for loops and while loops both have that same kind of domain thing, that if a variable is defined anywhere in the loop statement or body, then it's existence is limited to that "scope" (even if you are not using brackets).

In the past, that wasn't so, you could use the variable outside of the loop. But eventually the standard made the variable's scope confined to the loop. But some compilers, like MSVS, allow you the choice of having the compiler recognize the variable outside of the loop or forcing compliance with the standard. Of course you would want it to force compliance to the standard, unless you were compiling old source code that expected the variable to still be in scope outside of the loop.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.