Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

184
Visualizações
Code compiles despite having arithmatic operations in `case` statement. Aren't those not allowed there in C?

I was just practicing C and I found a program that has arithmetic operators used in case statement. But I've learned that arithmetic operations cannot be used in such place.
Then how is this program working?

#include <stdio.h>

int main()
{
    int ch = 'a' + 'b';

    switch (ch) {
        case 'a':
        case 'b':
            printf("You entered b \n");

        case 'A':
            printf("a as in ashar \n");

        case 'b'+'a':
            printf("You entered a and b \n");
    }

    return (0);
}

According to me the variable ch will store ASCII values of character 'a' + 'b', i.e. ch = 97 + 98 that becomes ch = 195;
The switch(ch) will match to case with 195, i.e. case 'a' + 'b'.

But the problem is how can we use arithmetic operators in case against rules of the C language?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

They are allowed no problem as long as they are integer constant expression.

From C99 standard § 6.8.4.2 point 3:

The expression of each case label shall be an integer constant expression (...)

And § 6.6 point 6 describes it as:

An integer constant expression shall have integer type and shall only have operands that are integer constants, enumeration constants, character constants, sizeof expressions whose results are integer constants, and floating constants that are the immediate operands of casts. Cast operators in an integer constant expression shall only convert arithmetic types to integer types, except as part of an operand to the sizeof operator.

And § 6.6 point 2 says:

A constant expression can be evaluated during translation rather than runtime, and accordingly may be used in any place that a constant may be.

In § 6.2.5 point 14 we read:

The type char, the signed and unsigned integer types, and the enumerated types are collectively called integer types. The integer and real floating types are collectively called real types.

And also in § 6.4.4.4 point 2:

An integer character constant is a sequence of one or more multibyte characters enclosed in single-quotes, as in 'x'. (...)

All elements of 'a' + 'b' expression are known at compile time.
Values written in single quotes are integers, so characters are also just integers.
Compiler can evaluate the expression and just replace it with the resulting 195.

over 4 years ago · Santiago Trujillo Relatório

0

There's nothing in the language that prevents using the + operator in a case.

The requirement is that the case value be an integer constant expression. Such an expression cannot contain an assignment, increment, decrement, function call, or comma operator, but other operators are allowed as long as each subexpression is a constant.

Section 6.8.4.2p3 of the C standard describes the requirements for a case:

The expression of each case label shall be an integer constant expression and no two of the case constant expressions in the same switch statement shall have the same value after conversion

Section 6.6p6 describes an integer constant expression:

An integer constant expression shall have integer type and shall only have operands that are integer constants, enumeration constants, character constants, sizeof expressions whose results are integer constants, _Alignof expressions, and floating constants that are the immediate operands of casts. Cast operators in an integer constant expression shall only convert arithmetic types to integer types, except as part of an operand to the sizeof or _Alignof operator.

And section 6.6p3 describes the constraints on operators in a constant expression:

Constant expressions shall not contain assignment, increment, decrement, function-call, or comma operators, except when they are contained within a subexpression that is not evaluated.

over 4 years ago · Santiago Trujillo Relatório

0

According to the standard (C99)

The expression of each case label shall be an integer constant expression and no two of the case constant expressions in the same switch statement shall have the same value after conversion. There may be at most one default label in a switch statement. (Any enclosed switch statement may have a default label or case constant expressions with values that duplicate case constant expressions in the enclosing switch statement.)

A constant expression can be evaluated during translation rather than runtime, and accordingly may be used in any place that a constant may be.

Expression 'b'+'a' will be translated at compile time and is therefore a constant expression, which, as you have noted, evaluates to 195.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda