Click here to Skip to main content
13,143,774 members (31,286 online)
Rate this:
Please Sign up or sign in to vote.
See more:
#include <stdio.h>
typedef enum{
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 1:59am
Updated 27-Mar-13 2:00am
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Because you defined a type. Thus implicit type casting won't work. See:[^]
Rate this: bad
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
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.
Lygatto Zenki 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.
Lygatto Zenki 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
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

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web02 | 2.8.170915.1 | Last Updated 27 Mar 2013
Copyright © CodeProject, 1999-2017
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