jamji
jamji

Reputation: 27

c++ array undeclared identifier error

I'm just pure C user.

I'm trying to implement with c++. But I have hard understand point with array.

The code

Question1

...
float *input = read_file(arg[1], ..);
for(;)
{
  float *buf = input;
  buf[c] = 1;
}

for(;)
{
  buf[c] = 1;
}  

As you can see above code, there are not exist buf declare. But There are error like this 'buf' undeclared identifier. I don't understand why this get error? Should I have to declare identifier every time?

Question2

...
float *input = read_file(arg[1], ..);
for(;)
{
  float *buf = input;
  buf[c] = 2;
}

for(;)
{
  float *buf = input;
  buf[c] = 1;
}  

If I modify the first buf array value, then the modified array value affect to second buf array. I don't understand. I have a new declare buf at second for sentence but still the modified value are affect to sencond buf array.

Upvotes: 0

Views: 2767

Answers (1)

vsoftco
vsoftco

Reputation: 56557

You should understand how scopes work in C/C++. A variable declared in a scope is visible only inside that scope and inner scopes. In your case, you declare buf inside the local scope of the first for loop. It is not visible in the other for scope, as the scopes are distinct. As mentioned in the comments, you need to make the variable visible to both for scopes. The only solution: declare it in the outer scope of the for loops.

EDIT

You asked why can you modify the input via a variable visible in the local scope. Well, your variable is a pointer float* buf that points to input. The latter is declared outside the scope, so it is visible by both for loops (their scope is enclosed, so they see the "outside world"). So, you can access it via your local pointer, and modify it accordingly.

The rule of thumb: from your house you can see the world, but the world cannot see inside your house (at least, if you're careful, and C/C++ compilers are quite careful).

Upvotes: 1

Related Questions