Thread: Proper Format

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    23

    Proper Format

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #define LOOPNUM 42 //just a way to keep a loop going infinitely without a GOTO
    /***********************************************/
    /*  The point of this program is to create a   */
    /*  variety of different functions that can be */
    /* called through main.  It's really just going*/
    /* to be every C program I make made so that I */
    /*     can call any one of them at a whim.     */
    /***********************************************/
    int inputnum; //main()'s scanf input variable
    /**********************/
    /*        Main        */
    /**********************/
    int main()
    {
        printf("Okay.  This is a computer program that is specifically geared toward a \ncompendium of all the useless things I can do with the C Programming language.\n");
        printf("Remember.  The number corresponds to a certain function.  There is a quit \nfunction as well.  Just type in '0'.\n");
        printf("Also, remember.  This works as a command line would.  Once you finish, a \nnew line appears.  Then, you can put something else in.\n\n");
        printf("Hello, world!-----------------------------------------------------------1\n");
        printf("2-way temperature converter---------------------------------------------2\n\n");
        while (1)
        {
        printf("-->");  //this pointer looks nice, doesn't it?
        inputnum = 100; //in order to reset it to a value every time, so that I don't get an infinite loop
        scanf("%d", &inputnum);
        skipgarb();
        switch(inputnum)  //first time using switch, this is probably not very good form
            {
                case 1 : helloworld();
                        break;
                case 2 : tempconvert();
                        break;
                case 0 : exit(0);
                default: printf("Uhhhmmm...well, this is awkward.  Please, try again.\n");
                        break;
            }
        }
    return 0;
    }
    /********************************************************************************************************************************
    ****************************************************/
    skipgarb()  //skips user input garbage
    {
        while (getchar() != '\n')
            {
            ;
            }
    }
    /********************************************************************************************************************************
    ****************************************************/
    helloworld() //exactly as it says
    {
        printf("Hello, world!\n");
    }
    /********************************************************************************************************************************
    ****************************************************/
    tempconvert() //I'm having some problems with this one right now
    {
        int z;
        int x = LOOPNUM;
        printf("Okay.  Start by putting in a number.  Enter 1 for a fahrenheit to celsius \nconversion, and enter 2 for a celsius to fahrenheit conversion.  As always, put in 0 to 
    exit.\n");
        while (x = LOOPNUM)
        {
            int m;
            printf("-->");
            int z = 100; //see line 26
            scanf("%d", &z);
            skipgarb();
            switch(z)
            {
                case 1 : fahrtocels();
                        x = 1;
                        break;
                case 2 : celstofahr();
                        x = 1;
                        break;
                case 0 : system("cls");
                        main();
                        x = 1; //I know i won't need this.  Just a precaution in case of the (supposedly) impossible possibility of exiting from main but not the program via scanf input.
                        break;
                default: printf("Mmmmmm...try again.  Remember.  1, 2, or 0.");
                        break;
            }
        }
    }
    /********************************************************************************************************************************
    ****************************************************/
    fahrtocels() //convert fahrenheit to celsius
    {
        float fahrenheit;
        float answer;
        printf("Enter your fahrenheit value.\n");
        scanf("%f", &fahrenheit);
        answer = 5.0 / 9.0 * (fahrenheit - 32); //don't you just love math?
        printf("%f\n", answer);
    }
    /********************************************************************************************************************************
    ****************************************************/
    celstofahr() //convert celsius to fahrenheit
    {
        float celsius;
        float answer;
        printf("Enter your celsius value.\n");
        scanf("%f", &celsius);
        answer = (9.0/5.0)*(celsius+32);
        printf("%f\n", answer);
    }
    So, a few things:

    1. Is it against so-called "standards" to call main?

    2. Is there is distinguishing mark as to when to use if statements vs. a switch?

    3. Anything else I might have done wrong?

    4. Oh, and who makes the official programming standards?

    Because, this program works. But, is it 'right' by the standards, and by what other programmers will consider 'right'? It looks nice to me, but is it well-written and easy to read?

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    1. Is it against so-called "standards" to call main?
    This falls outside of my realm of knowledge - however, there are others here who could give a proper answer. Some brief research shows that, in some versions of the C standard, this is not considered illegal. However, as you're a beginner, this is definitely something I would advise against using.

    2. Is there is distinguishing mark as to when to use if statements vs. a switch?
    There are no hard and fast rules (that I'm aware of) to determine which is better to use - it's something that comes with experience. If you have a variable, and [practically] each possible value will require different behavior, then a "switch" statement is likely the best choice. If you want to use (function or expression) evaluation in the argument of a conditional statement, than an "if" statement is likely the best choice.

    Code:
    // Example:
    
        int month = (some value);  // possible range of 1 - 12
    
    // If the values can only yield two possible outcomes out of 12 possible values, "if" statements are best
    
        if(month <= 6)
            printf("First half of the year.");
        if(month >= 7)
            printf("Second half of the year.");
    
    // If the values will yield a unique outcome for all 12 possible values, a "switch" statement is the best.
    
        switch(month)
        {
            case 1:  printf("January");  break;
            case 2:  printf("February");  break;
            case 3:  printf("March");  break;
            case 4:  printf("April");  break;
            case 5:  printf("May");  break;
            case 6:  printf("June");  break;
            case 7:  printf("July");  break;
            case 8:  printf("August");  break;
            case 9:  printf("September");  break;
            case 10: printf("October");  break;
            case 11: printf("November");  break;
            case 12: printf("December");  break;
            default: break;
        }
    This example is clearly contrived, and only reflects one of many possible situations where the "if" versus "switch" question can come up - but I hope it illustrated how you should approach this question.

    3. Anything else I might have done wrong?
    For starters, you should check the warnings when you compile your code.

    Code:
    main.c||In function 'main':|
    main.c|27|warning: implicit declaration of function 'skipgarb'|
    main.c|30|warning: implicit declaration of function 'helloworld'|
    main.c|32|warning: implicit declaration of function 'tempconvert'|
    main.c|44|warning: return type defaults to 'int'|
    main.c|53|warning: return type defaults to 'int'|
    main.c|59|warning: return type defaults to 'int'|
    main.c||In function 'tempconvert':|
    main.c|63|warning: suggest parentheses around assignment used as truth value|
    main.c|72|warning: implicit declaration of function 'fahrtocels'|
    main.c|75|warning: implicit declaration of function 'celstofahr'|
    main.c|65|warning: unused variable 'm'|
    main.c|60|warning: unused variable 'z'|
    main.c|90|warning: return type defaults to 'int'|
    main.c|101|warning: return type defaults to 'int'|
    main.c||In function 'celstofahr':|
    main.c|108|warning: control reaches end of non-void function|
    main.c||In function 'fahrtocels':|
    main.c|97|warning: control reaches end of non-void function|
    main.c||In function 'helloworld':|
    main.c|55|warning: control reaches end of non-void function|
    main.c||In function 'skipgarb':|
    main.c|49|warning: control reaches end of non-void function|
    ||=== Build finished: 0 errors, 17 warnings ===|
    It's good programming practice to treat each warning as an error, and "correct" your code so these warnings are no longer present. Just focus on one at a time. Sometimes the warning is not a big deal, other times it can be a very big deal indeed - and yet other times, it's indicative of a larger more serious problem in the code. Always heed the warnings.

    Also:
    - Be more consistent with your indentation; it is there, but can definitely be improved upon
    - If you define your functions after "main()" then you should declare them before "main()"
    - Your functions need a return type (or "void" if they're not returning any data)
    - Your functions should list the arguments they are expected to receive in the parenthesis (or "void" if they're not taking arguments)
    - In your while loop, you're still using the assignment operator (=) and not the equality operator (==)
    - In "tempconvert()", you are updating a variable (x) for each correct situation in order to break the loop - the logic can be restructured such that you could only update one variable (when user input is bad) to keep the loop going

    4. Oh, and who makes the official programming standards?
    Again, this falls outside my scope of knowledge, but it appears that there are several organizations that have been responsible for maintaining the standard (from wikipedia):

    Several variants of the C language exist, and they continue to be refined by standards organizations. The original informal specification was published in a book by Ritchie and Brian Kernighan, and is referred to as "K&R" C. In 1989 the American National Standards Institute published a more formal description of "Standard C" called ANSI C (or "C89"), and the identical document was approved the next year by the International Organization for Standardization and dubbed "C90". ISO released extensions to the standard in 1999 known as "C99", and the latest stable specification is "C11" which was approved in December of 2011.
    Last edited by Matticus; 07-10-2012 at 10:27 PM.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Your program should never call main(). (or re-call it). If you need to return to either a menu function, then have main() call menu(), which calls whatever choices the user wants, and then simply returns to either main() or to the menu() function.

    main >> menu >> user's choice of functions, >> and then simply returns to menu and presents the user with his choices. When you choose quit option from the menu function, control returns (by itself), to main, and ends.

  4. #4
    Registered User
    Join Date
    Nov 2011
    Posts
    23
    Thanks. That was unbelievably helpful. I see where all those things can help. And, yeah. A bit dumb of me to fix one loop and not the other.

    Also, what warnings? I see your long list, but I'm getting this in build messages:

    ===Build finished: 0 errors, 0 warnings ===
    Last edited by Gigabitten; 07-10-2012 at 11:21 PM. Reason: Mistake

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You should increase the warning level of your compiler.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User
    Join Date
    Jul 2012
    Location
    Australia
    Posts
    242
    I am using Code::Blocks with gcc compiler, and it can't even build.

    Code:
    |In function ‘tempconvert’:|
    62|warning: missing terminating " character [enabled by default]|
    62|error: missing terminating " character|
    63|error: stray ‘\’ in program|
    63|error: request for member ‘n’ in something not a structure or union|
    63|warning: missing terminating " character [enabled by default]|
    63|error: missing terminating " character|
    64|error: expected ‘)’ before ‘while’|
    87|error: expected ‘;’ before ‘}’ token|
    ||=== Build finished: 6 errors, 2 warnings ===|

  7. #7
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Code:
    |In function ‘tempconvert’:|
    62|warning: missing terminating " character [enabled by default]|
    62|error: missing terminating " character|
    63|error: stray ‘\’ in program|
    63|error: request for member ‘n’ in something not a structure or union|
    63|warning: missing terminating " character [enabled by default]|
    63|error: missing terminating " character|
    64|error: expected ‘)’ before ‘while’|
    87|error: expected ‘;’ before ‘}’ token|
    ||=== Build finished: 6 errors, 2 warnings ===|
    It seems that you have a line break problem in line 62. Check for any newline characters in your string literal. If you want to split a line you have to use the backslash immediately followed by a newline character.
    You can also use the automatic concatenation of adjacent string literals:
    Code:
    printf("One string"
           "Another string");
    is the same as
    Code:
    printf("One stringAnother string");
    Bye, Andreas

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 04-13-2012, 07:50 PM
  2. Proper format/standard of C program?
    By zerokernel in forum C Programming
    Replies: 3
    Last Post: 11-17-2010, 01:15 AM
  3. proper use of ->
    By Anddos in forum C++ Programming
    Replies: 4
    Last Post: 11-24-2005, 10:56 PM
  4. What is Proper?
    By Flakster in forum C++ Programming
    Replies: 12
    Last Post: 10-04-2005, 11:56 AM
  5. Proper way to end a dialogbox.
    By spoon_ in forum Windows Programming
    Replies: 2
    Last Post: 01-06-2003, 05:47 PM

Tags for this Thread