-3

If assignment can be done as many times we want then why is it showing an error. It was not showing an error if the same code was inside main.

#include <stdio.h>
  int arr[2]; // array elements are initialized as zero
  arr[0]=5;
  arr[1]=10;
int main()
{ 
  return 0;
}
Stack
  • 235
  • 3
  • 15

3 Answers3

5

These two lines

arr[0]=5;   // Assignment. Not initialization.
arr[1]=10;  // Assignment. Not initialization.

are statements that can't be executed outside a function. In global space only declaration and definitions are valid.

int arr[2];  

is a definition and it is valid. Brace initializers can be used to initialize arr with desired values

int arr[2] = {5, 10};  
haccks
  • 104,019
  • 25
  • 176
  • 264
3

In global scope, assignment (initlialization) can be done only through brace enclosed list. You may not use a statement in global scope to initialize or assign variables seperately.

In order to solve the issues, you need to put below statements

arr[0]=5;
arr[1]=10;

inside a function body.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

If you are new to programming you should know that the compiling always starts at the main function. Any code outside the main function is called "unreachable code" unless it is called by the main function.

For example you can have another function outside the main function(with new variables) but it will not be executed unless you call for it in the main() function.

Variables always needs to be inside a function or they will be unreachable.

The only exception I know to this rule is Constants. You can assign a constant using #define, before the main() function but not after the main(). For example:

#define  LENGTH 100
#define WIDTH 50
void main()
  {
  }

I hope this helps.

Charlie
  • 3,113
  • 3
  • 38
  • 60