Pregunta

With the following code, I always get "VGA" as output ,when I intend to get "NOT VGA"

#include<stdio.h>
#include<conio.h>
#define ADAPTER NVGA
#if ADAPTER==VGA
 int main()
 {
 printf("VGA");
 getch();
 return 0;
 }
#else
     int main()
 {
 printf(" NOT VGA");
 getch();
 return 0;
 }
 #endif
¿Fue útil?

Solución

Question is, where are VGA and NVGA defined?

If they are not defined, they will equal 0 according to C standard (N1570 - 6.10.1 Conditional inclusion - paragraph 4):

After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers (including those lexically identical to keywords) are replaced with the pp-number 0, and then each preprocessing token is converted into a token.

Which means your comparison will be #if 0==0, which is identical to #if 1.

To fix this, you need to define both VGA and NVGA to have different values:

#define VGA  1
#define NVGA 2

Otros consejos

There are two possibilities, and I can't tell which. The most likely is that, because neither NVGA nor VGA is a #defined macro, they are both evaluated as zero in #if and therefore considered to be equal. (This is a rule of the language.) The second possibility is that your system's stdio.h or conio.h defines NVGA to VGA.

To find out which, compile this program and see what happens:

#include <stdio.h>
#include <conio.h>
/* these numbers are chosen at random */
#define NVGA 8446
#define VGA 13060
#define ADAPTER NVGA
int main(void)
{
#if ADAPTER == VGA
    puts("VGA");
#else
    puts("NOT VGA");
#endif
    getch();
    return 0;
}

If it produces the output you expected (i.e. "NOT VGA"), your problem is the first one. If you get an error about redefining NVGA or VGA, your problem is the second one.

Because NVGA itself hasn't been defined. Instead try this:

#define NVGA 0
#define VGA 1

#define ADAPTER VGA

#if ADAPTER==VGA
  /* insert VGA code here*/
#else
  /* insert NVGA code here*/
#endif
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top