Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
While there are already good answers, i want to give yet another reason to always use {}: Macros. Lets consider this code: #include <stdio.h> #define FOO(n) puts(n[1]); puts(n[0]); in...
Answer
#2: Post edited
- While there are already good answers, i want to give yet another reason to always use `{}`: Macros.
- Lets consider this code:
- ```
- #include <stdio.h>
- #define FOO(n) puts(n[1]); puts(n[0]);
- int main(int argc, char **argv)
- {
- if(argc>1)
- FOO(argv);
- }
- ```
You may expect that the Macro `FOO` is only executed when `argc>1`, but no, the code gets expanded to:- ```
- ...
- if(argc>1)
- puts(n[1]); puts(n[0]);
- ....
- ```
- Which is the same as:
- ```
- ...
- if(argc>1)
- puts(n[1]);
- puts(n[0]);
- ....
- ```
- Which probably wasn't the intention. While the macro `FOO` is written in a bad way (because it allows this error), this error could still have been prevented by using `{}` for the `if`.
- While there are already good answers, i want to give yet another reason to always use `{}`: Macros.
- Lets consider this code:
- ```
- #include <stdio.h>
- #define FOO(n) puts(n[1]); puts(n[0]);
- int main(int argc, char **argv)
- {
- if(argc>1)
- FOO(argv);
- }
- ```
- You may expect that the code inside the macro `FOO` is only executed when `argc>1`, but no, some of the code is always executed. The code gets expanded to:
- ```
- ...
- if(argc>1)
- puts(n[1]); puts(n[0]);
- ....
- ```
- Which is the same as:
- ```
- ...
- if(argc>1)
- puts(n[1]);
- puts(n[0]);
- ....
- ```
- Which probably wasn't the intention. While the macro `FOO` is written in a bad way (because it allows this error), this error could still have been prevented by using `{}` for the `if`.
#1: Initial revision
While there are already good answers, i want to give yet another reason to always use `{}`: Macros. Lets consider this code: ``` #include <stdio.h> #define FOO(n) puts(n[1]); puts(n[0]); int main(int argc, char **argv) { if(argc>1) FOO(argv); } ``` You may expect that the Macro `FOO` is only executed when `argc>1`, but no, the code gets expanded to: ``` ... if(argc>1) puts(n[1]); puts(n[0]); .... ``` Which is the same as: ``` ... if(argc>1) puts(n[1]); puts(n[0]); .... ``` Which probably wasn't the intention. While the macro `FOO` is written in a bad way (because it allows this error), this error could still have been prevented by using `{}` for the `if`.