HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMajor

Validity of macro for printf() call in a corporate environment

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
environmentcallvalidityformacrocorporateprintf

Problem

I wrote this program:

#include 
#define printS for(i=0;s[i];i++){printf("%c",s[i]);}

int i;
char s[] = "Hello World!\n";

void main()
{
  printS;
}


It outputs exactly what I want it to but I have no clue if this would be acceptable to use if I were working for a company.

Would this be considered a poorly written piece of code in a corporate environment?

Solution

-
Although the C standard can allow void main() under certain implementations, it's best to use int main() whenever possible. See this for more info on the return type of main().

-
A loop is not a good use of a macro:

#define printS for(i=0;s[i];i++){printf("%c",s[i]);}


It should instead be a function:

void printS()
{
    for (i = 0; s[i]; i++)
    {
        printf("%c",s[i]);
    }
}


#define is a pre-processor directive (or a macro) that will replace the designated piece of code with something else. While you can use this with loops, it's still discouraged as there are cleaner alternatives in C, such as functions.

-
Your two variables above main() are in global scope, which is almost always discouraged. Anything in global that's not a constant can be modified anywhere in the program, which can introduce bugs and hurt maintenance. You should keep variables as close in scope as possible, such as in functions. You can then pass them to other functions as needed.

Assuming this is pre-C99, i should be declared right before the loop. Otherwise, it should be initialized within the loop statement.

-
Functions in C that take no arguments should have a void parameter:

void main(void)


-
Consider adding more whitespace between operators for more readability.

Using your single-line loop as an example:

for(i=0;s[i];i++){printf("%c",s[i]);}


You could have something like this:

for (i = 0; s[i]; i++) { printf("%c", s[i]); }


Implementation with changes applied:

#include 

void printS(char s[])
{
    int i;
    for (i = 0; s[i]; i++)
    {
        printf("%c", s[i]);
    }
}

int main(void)
{
    char s[] = "Hello World!\n";
    printS(s);
}

Code Snippets

#define printS for(i=0;s[i];i++){printf("%c",s[i]);}
void printS()
{
    for (i = 0; s[i]; i++)
    {
        printf("%c",s[i]);
    }
}
void main(void)
for(i=0;s[i];i++){printf("%c",s[i]);}
for (i = 0; s[i]; i++) { printf("%c", s[i]); }

Context

StackExchange Code Review Q#54264, answer score: 25

Revisions (0)

No revisions yet.