Is if(TRUE) a good idea in C?

后端 未结 17 3389
忘了有多久
忘了有多久 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.

    0 讨论(0)
  • 2021-02-19 01:45

    You don't even need an if statement. You can create blocks with {}

    That should probably be a separate function however.

    Example here:

    #include <stdio.h>
    
    int
    main(int argc, char **argv) {
        int i = 0;
        {
            int i = 10;
            printf("%d\n", i);
        }
        printf("%d\n", i);
    }
    
    0 讨论(0)
  • 2021-02-19 01:45

    I don't think you need the if(true) portion.

    Just the { } are required to scope the variables.

    0 讨论(0)
  • 2021-02-19 01:45

    My answer is as follows:

    This makes seasoned programmers cringe at the very thought of it.

    0 讨论(0)
  • 2021-02-19 01:46

    Note that in C99 it is allowed to declare local variables in the middle of blocks.

    C99 is the version of the C standard from the year 1999; most modern C compilers support it.

    0 讨论(0)
提交回复
热议问题