0

I've just copied a code from a slide explain array creation, but from a lot of tries all come back the same errors "expected identifier or '('". Follows the code:

int example [] = { 1, 2, 3 };
for (int i = 0; i < 3; i++)
{ 
    printf("%i \n", example [i]);
}

What I'm loosing? Is needed further brackets or declaration of main function? The TF on the video say "You don't have to do, like, main, blah, blah, blah, whatever. I just want you to initialize the array and creates a for loop to print them..." (time: 29:55 in this video)

2 Answers 2

2

That code on its own won't compile because you don't have a main function. In the video, she is asking the students to write the code that will initialize the array and then print it out ... but she isn't expecting that snippet to actually compile and run.

2

If this is your complete code, then you are missing some structural elements.

The simple explanation is that there needs to be a main() function in your program to contain the code. You would also need the appropriate include statements for the functions (printf(), etc.) that you are using.

It doesn't error out on the first line because the compiler thinks that you are declaring a global variable. As soon as it hits the keyword for, it knows something is wrong, so you get the error.

Your code, with corrections, would be this:

#include <stdio.h>

int main(void)
{ 
    int example [] = { 1, 2, 3 };
    for (int i = 0; i < 3; i++)
    { 
        printf("%i \n", example [i]);
    }
}    

A review of program structure, particularly #include statements and main() would serve you well right now.

If this answers your question, please accept the answer to remove your question from the unanswered question pool. Let's keep up on forum maintenance. ;-)

1
  • Alright @Cliff B, I've make a search at stackexchange and find out that in C, unlike Java, usually a script file always have a main... this was my lack. Commented Jul 9, 2015 at 22:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .