Is if(TRUE) a good idea in C?

后端 未结 17 3456
忘了有多久
忘了有多久 2021-02-19 01:19

In the C programming language, it is my understanding that variables can only be defined at the beginning of a code block, and the variable will have the scope of the block it w

17条回答
  •  悲哀的现实
    2021-02-19 01:44

    I think you're working with some outdated assumptions. I've been coding straight C using GCC for a few months now, and you don't need to declare variables at the beginning of a block, even though the Second edition of K&R says you have to. You can declare your variable anywhere, like like this not-very-useful example:

    char* palstring;
    palstring = malloc(LARGEST_STRING);
    memset(palstring, 0, sizeof palstring);
    fgets(palstring, LARGEST_STRING, fin);
    
    char* cur = palstring;
    char letter;
    letter = *cur;
    

    So there's no need to do what you're suggesting. The language has moved on.

    Another good addition to the C language is Variable Length Arrays, which allow you to pass an array to a function along with its size. In the old days, all you could do was pass in a pointer.

提交回复
热议问题