C obfuscates the program

#include<stdio.h>


int main(){

        int main =22;
        printf("%d\n",main);
        return 0;
}

Output: 22 I define main as a function and a variable, even though the compiler does not give an error. It should give the error “error: redefinition of the“ core. ”I cannot understand why this code works.

+4
source share
4 answers

This will not give you an error, because it is mainnot a keyword. but main is define 2 times- Figuring rules come into play.

+7
source

The main function is in the global scope - while the main variable is defined within the main scope of the function. They are not on the same level, so there is no conflict.

int main=22; () - / .

Do

int main(){

    return 0;
}

int main =22;

, .

+3

Declaring a function maininside a function creates a new identifier in the scope of the function. It does not override a function mainthat is defined in the global scope.

+3
source
#include <stdio.h>
#include <string.h>


void stuff();
main()
{
   int val = 10;
   printf("from main: %d\n", val);

   stuff();

   printf("from main: %d\n", val);

   stuff();
}

void stuff()
{
    int val = 5;
    printf("from stuff: %d\n", val);
}

It doesn’t matter to define int val many times, since it does matter in which area it is defined, this will result in 10 5 10 5 output, no errors without bad behavior

0
source

Source: https://habr.com/ru/post/1535873/


All Articles