c++ - Using a typedef as a variable name not generating any error -


considering structure of data:

typedef struct {     float x;     float y; } point; 

and i'm using function permute coordinates:

point permute(point m) {     point n;     n.x = m.y;     n.y = m.x;     return n; } 

why declaring variable name (point) typedef not giving error?

int main(void) { point a; point b; int point = 7;  a.x = 0; a.y = 1; b = permute(a);  printf("a (%.2f, %.2f)\n", a.x, a.y); printf("b (%.2f, %.2f)\n", b.x, b.y); printf("point = %d\n", point);  return 0; } 

output: http://ideone.com/wcxbjd

a (0.00, 1.00) b (1.00, 0.00) point = 7 

scope.

an identifier declared in outer scope (in case, @ file scope, i.e., outside function) may redeclared in inner scope (in case, inside main function). inner declaration hides outer declaration until reach end of inner scope.

this applies declarations in general, not typedef names.

a simple example:

#include <stdio.h>  typedef struct { int x, y; } point;  int main(void) {     point p = { 10, 20 };     /* p of type point */      int point = 42;     /* hides typedef; name "point"        refers variable */      printf("p = (%d, %d), point = %d\n", p.x, p.y, point);     /* p still visible here; type name "point" not        because it's hidden. */ } 

the output is:

p = (10, 20), point = 42 

if modified above program move typedef same scope variable declaration:

#include <stdio.h> int main(void) {     typedef struct { int x, y; } point;     point p = { 10, 20 };     int point = 42;     printf("p = (%d, %d), point = %d\n", p.x, p.y, point); } 

we'd error; gcc says:

c.c: in function ‘main’: c.c:5:9: error: ‘point’ redeclared different kind of symbol c.c:3:34: note: previous declaration of ‘point’ here 

(the c language could have been defined permit this, second declaration of point hiding first rest of scope, designers apparently felt hiding declarations outer scopes useful, doing within single scope cause more confusion it's worth.)

a more complex example:

#include <stdio.h> int main(void) {     typedef struct { int x, y; } point;     { /* create inner scope */         point p = { 10, 20 };         /* type name hidden */         int point = 42;         printf("p = (%d, %d), point = %d\n", p.x, p.y, point);     }     /* we're outside scope of `int point`, type name        visible again */      point p2 = { 30, 40 };     printf("p2 = (%d, %d)\n", p2.x, p2.y); } 

such hiding not best idea; using same name 2 different things, though it's no problem compiler, can confusing human readers. allows use names @ block scope without having worry names might have been introduced @ file scope headers you've include`.


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -