-3
#include <stdio.h>

if(1)
{
}

int main() 
{
    printf("Hello world");
    return 0;
}
abelenky
  • 63,815
  • 23
  • 109
  • 159
  • 5
    You can only put executable code inside a function body. At the top-level, there is no execution, only declarations and static initializations. – Tom Karzes Aug 02 '22 at 00:08
  • 6
    When do you imagine would a while loop be entered? – Cheatah Aug 02 '22 at 00:15
  • 2
    "Why is the language the way it is" questions generally cannot be answered, considering C is fifty years old and the people who made the key design decisions aren't here. – zwol Aug 02 '22 at 00:27

2 Answers2

2

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.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38
0

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.

Neil
  • 1,767
  • 2
  • 16
  • 22