4
#include<stdio.h>


int main(){

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

output:22 I am defining main as function and variable both even though compiler is not giving error. It should give error "error: redefinition of ‘main’ " . I am not able to understand why this code is working.

1
  • Take a tour. Commented Apr 10, 2014 at 7:16

4 Answers 4

7

It will not give you an error because main is not a keyword. but main is define 2 times - Scoping rules come into play.

Sign up to request clarification or add additional context in comments.

2 Comments

but main is define 2 times . first as function and second as variable.
but main is define 2 times - Scoping rules comes into play.
3

The main function is in the global scope - while the variable main is defined within the function main scope. They're not at the same level, thus there is no conflict.

The int main=22; line tells the compiler to use (declare) the local variable main - there is no conflict / ambiguity.

Do

int main(){

    return 0;
}

int main =22;

on the other hand and you'll get an error.

Comments

3

The declaration of main inside the function creates a new identifier in the scope of the function. It does not override the main function which is defined in global scope.

Comments

0
#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 defining the int val many times as it matters in which scope it's defined, this will output 10 5 10 5 , no errror no bad behavior

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.