Kraken
Kraken

Reputation: 24243

Global variable definition in C

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?

Upvotes: 0

Views: 155

Answers (3)

tesseract
tesseract

Reputation: 901

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

Upvotes: 0

rullof
rullof

Reputation: 7442

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...)

Upvotes: 1

Sergey L.
Sergey L.

Reputation: 22562

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?

Upvotes: 3

Related Questions