My English is very poor...there must be a lot of mistake in my expressions.
but It would be very kind if you can answer my question...
3Q.

In c compiler ( vs 2010 express c++),
I tried the code as follow, 0 error 0 waring.
In C++, it is the redefinition error.

Why it allows the declare redefinition in c?

#include <stdio.h>

int a;
int a;

int main()
{
        a = 100;

        printf("fdfsa");
        scanf(&a);
}

Recommended Answers

All 2 Replies

Using the Gnu compiler:

1745% cc ook.c # C compiler
ook.c: In function ‘main’:
ook.c:11: warning: passing argument 1 of ‘scanf’ from incompatible pointer type
ook.c:11: warning: format not a string literal and no format arguments

1746% cc ook.cpp # C++ compiler
ook.cpp:4: error: redefinition of ‘int a’
ook.cpp:3: error: ‘int a’ previously declared here
ook.cpp: In function ‘int main()’:
ook.cpp:11: error: cannot convert ‘int*’ to ‘const char*’ for argument ‘1’ to ‘int scanf

C++ makes it an error to redefine a variable. C does not. I don't know why. If you turn the warning level high in C, I think it will at least warn you about the problem, otherwise you should probably get and use lint.

int a; counts as a tentative declaration in C. If you don't write in a default value, you can declare the variable again later. Try providing a value both times you declare it and you should get an error:

#include <stdio.h>

int a = 42;
int a = 42;

int main()
{
  a = 100;

  printf("fdfsa");
  scanf(&a);
}

You get the error in C++ because C++ doesn't have tentative declarations.

Also: Best practice in C is to only declare variables once. Otherwise, things can get funky really fast, especially if you have multiple declarations in different files... yuck.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.