Search code examples
cscopedeclarationidentifierreserved-words

Can "printf" be used as a variable name?


Rules for variable names in C are as follows:

  1. A variable name can only have letters (both uppercase and lowercase letters), digits and underscore.
  2. The first letter of a variable should be either a letter or an underscore.
  3. There is no rule on how long a variable name (identifier) can be. However, you may run into problems in some compilers if the variable name is longer than 31 characters. (source: [https://www.programiz.com/c-programming/c-variables-constants])

I'm wondering about whether, theoretically, if a single underbar(_) or double underbar(__) be used as a variable? and can printf or scanf be used as a variable?

While playing with the c compiler(Dev C++) and linux Ubuntu Vi, even if I used the above as a variable name, there weren't any errors or warnings.

The code I used is as follows:

#include <stdio.h>
int main(void){
   int scanf;
   int printf;
   int _;
   int __;
   return 0;
}

Solution

  • yes, they can be used. see:

    The code:

    ~> cat demo.c
    #include <stdio.h>
    
    void show(int i) {
       printf("Just for show: %i\n", i);
    }
    
    int main(int argc, char **args) {
       int printf = 42;
       int _ = 11;
       int __ = 22;
    
       (void)argc;
       (void)args;
    
       show(printf);
       show(_);
       show(__);
    
       return 0;
    }
    

    The compiling process with no errors:

    ~>  gcc -std=c99 -Wall -Wextra -pedantic -o demo demo.c
    

    The output:

    ~>  ./demo
    Just for show: 42
    Just for show: 11
    Just for show: 22