0

To avoid declaring flows of one-time-use variables, I like to proceed using as few variables as possible and recasting them like so:

int main()
{
    int i1;

#define cChar ((char)i1)
    cChar='a';
#undef cChar
}

Which gives me the famous "error : lvalue required as left operand of assignment".

After reading a bit about this issue on this forum, it was pointed out that since 4.0, the cast-as-lvalue was removed (https://gcc.gnu.org/gcc-4.0/changes.html).

However, I fail to understand the why behind this and I was wondering if there was an option (apparently not) or even an alternative to GCC that would accept this kind of operation, which has been working for ages on ye olde compiler (obviously not GCC, but like Borland C++).

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Shinkel
  • 11
  • 1
  • Related: [Is typecasting on lvalue of operation not allowed?](https://stackoverflow.com/q/30116881) and [Why does an lvalue cast work?](https://stackoverflow.com/q/15343276). – Brian61354270 Aug 30 '21 at 17:09
  • 5
    I'm not quite sure what you're trying to achieve, but I suspect that a sane, modern C compiler can basically make that optimization for you without having to resort to weird aliasing that has a high chance of actually breaking optimizations. – Joachim Sauer Aug 30 '21 at 17:10
  • Thanks for you answers, but I fail again to understand how casting is not an optimization in the way that having to declare only 1 variable that you reuse in the proper conditions avoids having to declare, say, 10 variables you'll use one time in the end, thus consuming less memory. So, you infer that this reuse of memory space is now handled by modern compilers? Well then, I'll give that a thought. Thanks! – Shinkel Aug 31 '21 at 05:56
  • What does the casting have to do with reusing a variable? Can you add an example? – ssbssa Aug 31 '21 at 10:18
  • Given this goes by my own understanding of C, it's very likely I'm wrong about this, but here goes (sorry about the formatting, I cannot seem to have it processed as code :( ) int i1; i1 = 2; #define cChar (char)i1 cChar='a'; //also using i1 without the need to declare a dedicated char #undef cChar #define pStr (((char)*)i1) pStr=malloc(16); sprintf(pStr,"string"); //same for a dedicated char * – Shinkel Aug 31 '21 at 10:55

0 Answers0