steady_progress
steady_progress

Reputation: 3731

comparing number with special character

Consider the following C-program:

#include <stdio.h>    
int main()
{
    char c;

    c = 65;
    if(c=='A') printf("condition true");
    return 0; 
}

As expected (since the ASCII code for A is 65 this program prints the statement "condition true").

Now consider the following C-program:

#include <stdio.h>   
int main()
{
    char c;

    c = 27;
    if(c==ESC) printf("condition true");
    return 0; 
}

Since the ASCII code for ESC is 27, I expected this program to print the statement "condition true", too. However, the program didn't even compile but gave back the following error message:

error: use of undeclared identifier 'ESC'

How can I check whether some number (e.g. 27) is the ASCII code for some special character (such as ESC, EOF, ...)?

Upvotes: 1

Views: 86

Answers (2)

chux
chux

Reputation: 153547

ESC is not defined in C to be a special character nor ESC. C does not even require ASCII, although that is by far the most common coding set used.

Create your own

#ifndef ESC
  #define ESC 27
#else
  #error prior esc definition
#endif

if (some_number == ESC) {
  puts("number is same as ASCII ESC");
}

Notice that A is not defined to be 65 either.

If code needs to test if a number is an ASCII A, use

#define ASCII_A 65
if (some_number == ASCII_A) {

If code needs to test if a number is an 'A', (Matches the A of the source coding set)

if (some_number == `A`) {

Upvotes: 1

dbush
dbush

Reputation: 224082

Only certain special characters are defined by the C standard in section 5.2.2:

  • \a: alert
  • \b: backspace
  • \f: form feed
  • \n: new line
  • \r: carriage return
  • \t: tab
  • \v: vertical tab

If the special character is one of these, you can use one of the above escape sequences in a character constant (ex. '\n') to compare against.

Upvotes: 1

Related Questions