Why can't we use if or for loop ,while globally in C

95 views Asked by At
#include <stdio.h>

if(1)
{
}

int main() 
{
    printf("Hello world");
    return 0;
}
2

There are 2 answers

0
Allan Wind On

if(1) {} is a (selection) statement (6.8.4) and statements are only allowed in function definitions (6.9.1). See Programming Language - C (draft) for the relevant sections, also refer to the informative Annex A.

0
Neil On

We could have had a similar mechanism to sh-scripts where it just goes though the file line-by-line, without main. However, having an agreed-upon entry-point allows compilers to abstract compiling from linking for multi-compilation-unit programmes and libraries.

Dennis Ritchie and Ken Thompson developed it after B. This was based on BCPL, developed by Martin Richards. This had a LET START(), much in the way of Fortran, from The FORTRAN Automatic Coding System:

a basic block is a stretch of program which has one entry point and one exit point

In that way, going from an sh-script to C is entirely possible, but not the other way around.