首页 文章

使用c中的#if创建程序模式

提问于
浏览
0

我正在尝试使用 #if#define 为程序创建两种模式,但第二种模式不起作用为什么呢?如果你能提出一个更好的方法,我会很感激 .

这是我的代码:

#include "Types.h"
#include <stdio.h>


void main (void)
{
    u32 m;
    u32 flag = 1;
    do 
    {
        printf("\nWelcome\nPress 1 for Admin mode\nPress 2 for User Mode\nYour Choice:");
        scanf("%d",&m);
        if (m==1)
        {
            #define m 1
            flag = 0;
        }
        else if (m==2)
        {
            #define n 2
            flag = 0;
        }
        else 
        {
            printf("\nInvalid number \nPlease Try again");
        }
    }while(flag);

//using conditional directive to run only the portion of the code for the slected mode  
#if m==1
printf("Welcome to admin mode");

#elif n==2
printf("Welcome to user mode");

#endif
}

3 回答

  • 2

    如果 #if 只能解释在预处理时已知的值,那么预处理器甚至可以在编译时之前解释 .
    它无法读取像 u32 m 这样的变量的值 .
    另一方面,预处理器 #define 也只在预处理时完成,它不会受到"then"分支或 if 的"else"分支的影响 .

    在代码块中(例如,如果是分支),甚至在函数内执行 #define 是不建议的 . 您没有指定代码行为异常,但如果 #if 始终执行管理模式,我不会感到惊讶 . 之前在文件中有一个 #define m 1 (无论运行时执行的路径是什么),因此proprocessor将采用第一个选项 .

  • 2

    在C语言中,预处理器使用以“#”开头的指令 . 预处理器在编译之前扫描您的文件,以便“变量”m被硬编码,并且您无法在运行时更改它(当您运行程序时) . 此外,声明了“m”变量但未使用 . 要在运行时更改程序的行为,您应该使用标准变量并使用switch-case来检查变量的值并运行相应的代码 .

    我还建议使用由“int”或“char”等语言定义的标准类型,因为它们通过不同的体系结构具有更好的可移植性 .

    你的代码可能是这样的

    #include <stdio.h>
    
    int main (void)
    {
      int m;
      do
      {
        printf("\nWelcome\nPress 1 for Admin mode\nPress 2 for User Mode\nYour Choice:");
        scanf("%d",&m);
        if (m == 1)
        {
          printf("Welcome to admin mode");
          return 0;
        }
        else if (m == 2)
        {
          printf("Welcome to user mode");
          return 0;
        }
        else
        {
          printf("\nInvalid number \nPlease Try again");
        }
      }while(m != 1 || m != 2);
      return 0;
    }
    
  • 2

    #define 和ifs是预处理器宏的一部分 . 考虑它们的一种方法是想象编译器会通过您的文件并将其作为编译的早期步骤进行剪切和粘贴 . 当您将例如 PI 定义为3时,它将粘贴3 's everywhere in your code that you have written the PI. This then tells us that it won' t在运行程序时m == 1或2的哪个分支出现 - 所有预处理器编辑都已完成!

    在某种模式下构建程序的一种方法是在编译时使用标志,例如 -D DEBUG . 请注意,我们不能使用它来选择已编译的程序中的模式 .

    预处理器选项:-D =将隐式#define添加到预定义缓冲区中,该缓冲区在预处理源文件之前读取 .

相关问题