#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    3
    Rep Power
    0

    First C program crashing (switch statement)


    Hi there,
    just looking for a little guidance. It is my first attempt at a very basic practice program, so please be gentle

    int main ()
    //player guesses a number, compared to set values for
    //winnings, jackpots and bankrupt
    {
    int winnings = 0;
    int roll = 0;
    puts("Roll : ");
    scanf("%i", roll);
    switch(roll)

    {
    case 50:
    winnings = winnings + 50;
    break;
    case 75:
    winnings = winnings + 80;
    puts ("Boom-ting!");
    break;
    case 100:
    winnings = winnings++;
    break;
    default:
    winnings = winnings - 10;
    puts ("Bankrupt");
    break;

    }
    printf("%i", winnings);
    return 0;
    }


    the program complies fine but crashes after a value for 'roll' is input by the player.

    Any input would be greatly appreciated.

    Many thanks

    ZD
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,417
    Rep Power
    1871
    First, use [code][/code] tags around your code, so formatting is preserved, like so.
    Code:
    #include <stdio.h>
    int main()
    //player guesses a number, compared to set values for
    //winnings, jackpots and bankrupt
    {
      int winnings = 0;
      int roll = 0;
      puts("Roll : ");
      scanf("%i", roll);
      switch (roll)
      {
      case 50:
        winnings = winnings + 50;
        break;
      case 75:
        winnings = winnings + 80;
        puts("Boom-ting!");
        break;
      case 100:
        winnings = winnings++;
        break;
      default:
        winnings = winnings - 10;
        puts("Bankrupt");
        break;
      }
      printf("%i", winnings);
      return 0;
    }
    Next, turn up the warning level on your compiler.
    Code:
    $ gcc -Wall -Wextra -Werror baz.c
    baz.c: In function ‘main’:
    baz.c:9:3: error: format ‘%i’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Werror=format]
    baz.c:20:14: error: operation on ‘winnings’ may be undefined [-Werror=sequence-point]
    cc1: all warnings being treated as errors
    1. You forgot the & on your scanf
    2. Just say either winnings++ or winnings = winnings + 1;
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    3
    Rep Power
    0

    Thumbs up


    Thank you - that was really helpful!

    My first program works

    Huge appreciation friend

IMN logo majestic logo threadwatch logo seochat tools logo