Thread: Declaring a void variable and typecasting it later

  1. #1
    Registered User
    Join Date
    May 2012

    Question Declaring a void variable and typecasting it later

    Hey guys,

    I was wondering if its possible to do something like this in c:

     void variable = 'c';
    if (xyz)    {
    char variable2 = variable; 
    if (not xyz)    {
    int variable3 = variable;
    I tried it and gcc warned me, while stating that it was enabled by default, so I am not sure. Thanks in advance for any help!!

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    No, although you can use a pointer to void to point to a char or to an int, with the choice determined at run time.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    Use a union.
    struct foo {
      int flag;
      union {
        char c;
        int i;
      } v;
    struct foo var;
    if ( var.flag ) {
      var.v.c = 'a';
    } else {
      var.v.i = 42;
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Typecasting and void pointers...
    By k2712 in forum C Programming
    Replies: 1
    Last Post: 08-04-2008, 10:07 PM
  2. typecasting void *pointers
    By Eavan Hyde in forum C Programming
    Replies: 16
    Last Post: 07-03-2006, 08:33 AM
  3. Passing a variable in void to another void function
    By stevedawg85 in forum C++ Programming
    Replies: 5
    Last Post: 05-05-2006, 06:17 PM
  4. Typecasting a void* to a function pointer
    By Procyon in forum C++ Programming
    Replies: 2
    Last Post: 01-14-2004, 05:43 PM
  5. What's the use of declaring a pointer to void ?
    By Nutshell in forum C Programming
    Replies: 2
    Last Post: 01-15-2002, 05:00 AM