I am new to C++ and i don't understant this error message i am recieving. Could you show me the solution? ([Error] name lookup of 'n' changed for ISO 'for' scoping [-fpermissive]) line 25, col 17 (the 'n' is the problem)

#include <cstdlib>
#include <iostream>
#include <math.h>
#include "dp_lib.h"

using namespace std;

int main()
{
    double pi=3.141592653589793238462643383279502884197169399375;
    float value;
    unsigned long length = 44100; // sample rate
    int freq = 1000;
    int t = 1;

    int amp = 10;  // size of the wave

    FILE* fp = fopen("data.csv", "wb"); // open file 

// loop to generate audio samples
    for(int n=0; n < length; n++) //where n is the step 
    int t = n/freq;           //t/freq
        {
      value = amp*sin(2*pi*freq*t);
      write_CSV(n, value, fp);
      cout << n << "\t" << value <<"\n"; 
    }

    fclose(fp);         // close file
    free(fp);         // release memory

  cout << "\n\n";
  system ("pause");
}

Thank you very much

This is one of those sneaky bugs. Basically it is telling you that if you declare a variable in the for loop, it only lasts as long as the for loop. At first glance it looks like you only ever use 'n' inside your loop. You are wrong. Let me re-write your code with some different whitespace-ing and you will see why:

// loop to generate audio samples
for(int n=0; n < length; n++) //where n is the step |Start of For loop
    int t = n/freq; //t/freq                        |End of For loop


{//random unnecessary block
    value = amp*sin(2*pi*freq*t);
    write_CSV(n, value, fp);
    cout << n << "\t" << value <<"\n";
}

The reason for this is that loops, and if statements, only last for 1 statement (IE: until the first semi-colon). This would make them really hard to use, except that C++ provides Blocks. Basically any time you say {/*code here*/} it takes all of your code and turns it into one statement. This is true of every time you use the curly braces (as far as I know). However functions often still require them (my compiler doesn't, but ideone does).

Thus the fix is simple: move line 22 into the block:

// loop to generate audio samples
for(int n=0; n < length; n++) //where n is the step |Start of For loop
{
int t = n/freq; //t/freq
value = amp*sin(2*pi*freq*t);
write_CSV(n, value, fp);
cout << n << "\t" << value <<"\n";
} //|End of For loop
commented: Fine eye! +15
commented: nice explanation +14
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.