Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What are the difference between Initialization and Assignment wrt (1) compilation and runtime (2) Global scope and Local scope (3) Syntax style in C

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading