scriptscale
scriptscale

Reputation: 83

Getting error: "variable cannot appear in a constant-expression"

I've made a basic code in C-Free5.0, if do same as in if statement all showing good. but when I use a switch it gives the error: 'per' cannot appear in a Constant-expression, why its give the error?

#include<stdio.h>
#include<conio.h>
int main()
{
    int urdu=134;
    int eng=112;
    int isl=72;
    int ps=58;
    int maths=137;
    int phy=128;
    int chem=120;
    int bio=115;

    int total=(urdu+eng+isl+ps+maths+phy+chem+bio);
    int per=(total*100)/1050;

    printf("Urdu=               %d\n", urdu);
    printf("English=            %d\n", eng);
    printf("Islmiyat=           %d\n", isl);
    printf("Pakistan Studies=   %d\n", ps);
    printf("Mathematics=        %d\n", maths);
    printf("Physics=            %d\n", phy);
    printf("Chemistery=         %d\n", chem);
    printf("Biology=            %d\n\n", bio);

    printf("Percentage:         %d\n",per);

    switch(per)
    {
        case (per>80):
        printf("A+");

        case (per>70):
        printf("A");
    }
    getch();
}

Upvotes: 0

Views: 371

Answers (1)

Mureinik
Mureinik

Reputation: 311978

A switch-case is a short hand for a series of ifs checking the equality of a variable to a series of constants. You can't use it in the way you specified. Instead, you could just use plain old if statements:

if (per > 80) {
    printf("A+");
else if (per > 70) {
    printf("A");
}

Upvotes: 4

Related Questions