Declaring a void variable and typecasting it later

This is a discussion on Declaring a void variable and typecasting it later within the C Programming forums, part of the General Programming Boards category; Hey guys, I was wondering if its possible to do something like this in c: Code: void variable = 'c'; ...

  1. #1
    Registered User
    Join Date
    May 2012
    Posts
    4

    Question Declaring a void variable and typecasting it later

    Hey guys,

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

    Code:
     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
    Location
    Singapore
    Posts
    22,268
    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.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    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
    Location
    The edge of the known universe
    Posts
    32,823
    Use a union.
    Code:
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

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, 11:07 PM
  2. typecasting void *pointers
    By Eavan Hyde in forum C Programming
    Replies: 16
    Last Post: 07-03-2006, 09: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, 07: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21