Click here to Skip to main content
15,881,380 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include <stdio.h>
typedef enum{
red=1,blue,green
}color;

void set_color(color *c)
{
  *c = blue;
}

int main()
{
  //int a = 3;
  //set_color(&a);//why this error?
  //set_color((color *)(&a));//It is right
  color c = red;
  set_color(&c); // this is right;
  return 0;
}

i use gcc -S to view the assemble language with set_color((color *)(&a)) and it is the same with set_color(&c),but why gcc does not do the convertion automatically?
Posted
Updated 27-Mar-13 2:00am
v2

Because you defined a type. Thus implicit type casting won't work. See: http://en.cppreference.com/w/cpp/language/implicit_cast[^]
 
Share this answer
 
Because it is trying to prevent you making a mistake, and you not realizing it.
When you write
C++
set_color((color *)(&a));
You are explicitly converting it - telling the compiler "this is the value I wanted to send, I know what I am doing" so it lets it through.

When you write
C++
set_color(&a);
It could be a mistake - you might not have realised that "a" was not a color at all. So it raises an error so you can fix the problem before it becomes a run time problem and causes an odd bug.
 
Share this answer
 
Comments
Keanu L 27-Mar-13 8:16am    
In gcc, the int and the emun are allocated the same memory size 4 bytes, so it should be safe.
OriginalGriff 27-Mar-13 8:30am    
Doesn't matter - it will be safe because all enums (unless sepcifically stated otherwise) are based on an integer. The compiler is telling you that this could be an unsafe operation from a program logic point of view, rather than from a execution run-time-error point of view.
Keanu L 27-Mar-13 8:52am    
Thank you for your explanation. I have underundered the problem.You are right , from the view of compiler i should consider the program logic.
In C (and C++), the datatypes 'int' and 'enum' are partly typesafe. For example:

C
typedef enum {E0 = 0, E1 = 1} ENUMtype_t;

ENUMtype_t e = E0;  // legal
int i = 0;          // legal
i = E0;             // legal
e = 0;              // legal(!)
e = 1;              // error(!)
e = i;              // error
e = (ENUMtype_t) i; // legal
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900