Unknown mistake from a Textbook example

Hello guys. I'm involved with C++ for about 3 weeks by now. So far i enjoy the learning process. Something strange occured today tho. I copied this example from Arrays chapter and i couldn't compile it for some reason. Maybe the book i read is outdated, or my CodeBlocks IDE is messing with me. What do you think?

#include <iostream>
#include <cstdlib>
using namespace std;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
int main()
{
    srand(2);
    int nums[12];

    cout<<" Array of Random Numbers: ";

    for(int &x: nums) // this line is marked on CodeBlocks
    {
        x=rand()%10;
        cout<<x<<" ";
    }
    cout<<endl;
    int length = 0;

    for(int &x: nums)
    {
        length++;
    }
    cout<<"Size of Array: "<<length<<endl;
    cout<<"Checking the content of Array: ";

    for(int k=0; k<length; k++)
    {
        cout<<nums[k]<<" ";
    }
    cout<<endl;
    system("pause");
    return 0;
}
Last edited on
Are you using C++11 or newer? Range based for-loops (lines 8-12 and 16-19) were introduced in it, so if you are not that is what is causing the error.
I actually did a little checking. Apparently i had to go Settings and mark: "have g++ follow the C++ 11 ISO C++...". Now it compiles perfectly!

Ironicly while googling i found the answer here: http://www.cplusplus.com/doc/tutorial/introduction/codeblocks/ !

I thought that my compiler is set by default for C++ 11 version, apparently not! :D
Glad you got it worked out; Best of luck with your future projects!
I thought that my compiler is set by default for C++ 11 version, apparently not! :D


No, by default g++ defaults to -std=gnu++XX, where XX is 98 until the 6.0 version of the compiler where the default changed to -std=gnu++14. The "gnu" allows compiler specific features to be used, to disable these you need to use -std=c++XX where the XX is one of the following1 98, 11, 14, or 17. You should also use -pedantic or -pedantic-errors along with the -std=c++XX to eliminate all compiler specific hacks from being used.

1: If your version of the compiler supports those specific standards, see the documentation for your specific version to for specifics.
Topic archived. No new replies allowed.