0

In my code below

#include<stdio.h>
int a;
a=3;

void main(){
printf("%d",a);
}

Why am I getting the warning,

a.c:3:1: warning: data definition has no type or storage class [enabled by default]

In another case, when I have

#include<stdio.h>
#include<stdlib.h>
int* a;
a=(int*)malloc(sizeof(int));

void main(){
*a=3;
printf("%d",a);
}

I get error: conflicting types for ‘a’, and also warning as

warning: initialization makes integer from pointer without a cast [enabled by default]

Why?

Kraken
  • 23,393
  • 37
  • 102
  • 162

3 Answers3

3

You can only initialise global variables with constants and it has to be done during the declaration:

 int a = 3; // is valid

If you need to initialise a global variable with the return of malloc then that has to happen during runtime.

int *a;

int main() {
  a = malloc(sizeof(*a));
}

Also please do not cast the return type of malloc in C. This is a common source of errors. Do I cast the result of malloc?

Community
  • 1
  • 1
Sergey L.
  • 21,822
  • 5
  • 49
  • 75
1

The top section (outside any function) allow only definitions, declarations and initialization but this line:

a=3;

is an assignment statment and the compiler considere it as a new declaration as you didn't specify any type for a that's why you get the error (... no data type...) and also as a is already declared as int you get the error (...conflicting types...)

rullof
  • 7,124
  • 6
  • 27
  • 36
0

external and global variables must be defined exactly once outside of any function.

tesseract
  • 891
  • 1
  • 7
  • 16