calm-tedesco
calm-tedesco

Reputation: 256

'Segmentation fault (core dumped)' with case

'Segmentation fault (core dumped)' appears when I execute the following program. However, if I use the if...else statement it doesn't give me any error. What is the reason of the error message in this case? How can I use the case statement without error?

#include <iostream>
#include <cstdlib>
using namespace std;

int main(int argc, char* argv[]){

/*
    if (argc == 1){
        cout << argv[0] << endl;
    }else
    if (argc == 2){
        int n;
        n = atoi(argv[0]);
        cout << n << endl;
    }
*/
    switch (argc){
        case 1:{
            cout << argv[0] << endl;
        }
        case 2:{
            int n;
            n = atoi(argv[1]);
            cout << n << endl;
        }
    }

    return 0;
}

Upvotes: 3

Views: 831

Answers (1)

WhiZTiM
WhiZTiM

Reputation: 21576

There is no break within your switch block. Hence, every case will fallthrough. This invokes Undefined Behavior when argc is 1. You should break out of the switch when you do not want a fallthrough.

switch (argc){
    case 1:{
        cout << argv[0] << endl;
        break;
    }
    case 2:{
        int n;
        n = atoi(argv[1]);
        cout << n << endl;
        break;
    }
}

From C++17, when compilers warn you about implicit fallthroughs (its not required to), you can use the attribute [[fallthrough]] to declare that your fallthrough is intentional.

Upvotes: 4

Related Questions