Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C GCC
#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 27-Mar-13 2:59am
Edited 27-Mar-13 3:00am
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Because you defined a type. Thus implicit type casting won't work. See: http://en.cppreference.com/w/cpp/language/implicit_cast[^]
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Because it is trying to prevent you making a mistake, and you not realizing it.
When you write
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
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.
  Permalink  
Comments
Lygatto Zenki at 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 at 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.
Lygatto Zenki at 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.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

In C (and C++), the datatypes 'int' and 'enum' are partly typesafe. For example:
 
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
  Permalink  

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



Advertise | Privacy | Mobile
Web01 | 2.8.141220.1 | Last Updated 27 Mar 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100