Advertisements
Here is Define.c
#include "Define.h"
// statement1
Format date_format = { "YYMMDD", "%02u%02u%02u", 6, 3 };
// Either above statement 1 or below statement2
// statement2
Format date_format;
strcpy(date_format.format, "YYMMDD"); // line2
strcpy(date_format.scanformat, "%02u%02u%02u"); // line3
date_format.scansize = 3; // line4
date_format.printsize = 6; // line5
Here is Define.h
#ifndef _DEFINE_H
#define _DEFINE_H
typedef struct Format
{
char format[256];
char scanformat[256];
unsigned int printsize;
unsigned int scansize;
} Format;
extern Format date_format;
#endif
main.c
#include <stdio.h>
#include "Define.h"
int main(int argc, char* argv[])
{
printf(date_format.format);
getchar();
return 0;
}
I either using statement1 or statement2 at a time but only statement1 is working while statement2 is not. So is it compulsory to use syntax style of statement1 for initialization in global scope? And what if the datatype is inbuilt, is there any syntax compulsion for initialization?
>Solution :
Only declarations and definitions may appear at file scope. This is therefore valid at file scope:
Format date_format = { "YYMMDD", "%02u%02u%02u", 6, 3 };
Because it is a definition with an initializer using constants.
These are not valid at file scope:
strcpy(date_format.format, "YYMMDD"); // line2
strcpy(date_format.scanformat, "%02u%02u%02u"); // line3
date_format.scansize = 3; // line4
date_format.printsize = 6; // line5
Because they are executable statements, not declarations, and such statements may not appear outside of a function.