0

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);
}

Edited by mike_2000_17: Fixed formatting

3
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by gusano79
0

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.

1

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.