Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is if(TRUE) a good idea in C?

Tags:

c

if-statement

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 was declared in. With that in mind, I was wondering whether it is considered bad practice to artificially create a new scope as in this example:

void foo()
{
     ... Do some stuff ...

     if(TRUE)
     {
         char a;
         int b;

         ... Do some more stuff ...
     }

     ... Do even more stuff ...
 }

Assuming TRUE is set to 1 in a macro definition, would this code be considered 'good code' or does it make seasoned programmers cringe at the very thought of it?

Thanks for your input!

EDIT: In response to some of the answers, the code I am working with needs to work with some pretty ancient legacy systems. While it would be nice to operate on an assumption of C99, we really can't guarantee that they will have it.

like image 815
Tim Avatar asked Feb 12 '09 15:02

Tim


People also ask

Can you use true in C?

A true boolean data type could be used for storing logical values, and would only have two legal values - "true", and "false". C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true.

Does if (- 1 in C is true or false?

In standard C, any non-zero (positive/negative) value is TRUE. So, (-1) evaluated as TRUE and, !(- 1) of-course evaluated as FALSE.

What is if 1 in C programming?

The if statement allows you to control if a program enters a section of code or not based on whether a given condition is true or false.


2 Answers

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);
}
like image 85
Philip Reynolds Avatar answered Oct 17 '22 06:10

Philip Reynolds


As far as I know you can create a scope without if.

Use just the braces like this:

{
    int x;

}

And I recommend against

if (TRUE)

since it hinders readibility.

like image 44
George Avatar answered Oct 17 '22 06:10

George