0

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?

1 Answers1

3

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Yes I already read those questions and answers but they don't fully cover my question particularly limitation of syntax for Initialization statement. Only this `Format date_format = { "YYMMDD", "%02u%02u%02u", 6, 3 };` style of intialization is valid and not the other one? – Rakesh Solanki May 03 '23 at 15:50
  • @RakeshSolanki The first is a definition with an initialization, and the rest are statements. Statements are not allowed outside of a function. – dbush May 03 '23 at 15:55