CrazyEngineers
  • ## operator in c language

    Updated: Oct 26, 2024
    Views: 1.2K
    Hello friends,
    can anyone explain about the ##operator in c language and how it works??
    0
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • Vishal Sharma

    MemberAug 23, 2014

    madhuri thalluri
    Hello friends,
    can anyone explain about the ##operator in c language and how it works??
    I think you couldn't find any documentation regarding this as it is very poorly documented and hence you had to post a question on that.
    Actually, ## is called the token pasting operator and concatenates the characters defined around it (excluding the white spaces). It is generally used in your definition macro.
    ex:
    #define my_name v ##       i ##s        ##hal
    the above statement will define my_name as vishal, hope you understood what happened above.

    ## can also be used to do beautiful things like executing your code without actually typing "main" anywhere in the code. However, Internally ## creates a string main. Take a look at this example, try copying it in an editor and run it See what happens

    #define vishal(s,t,u,m,p,e,d) m##s##u##t
    #define freak vishal(a,n,i,m,a,t,e)
    #include<stdio.h>
    
    int freak() {
        printf("hello world");
        getchar();
        return 0;
    }
    
    In the above code we define a function vishal with 7 parameters s,t,u,m,p,e,d whose task is to concatenate the parameters m,s,u,t. Now, in the second macro definition, we are calling the function vishal() as vishal(a,n,i,m,a,t,e), whose result is stored in a variable freak. When this executes, It concatenates the parameters m,s,u,t which are m,a,i,n in the calling function (line 2). So, freak now holds the string "main"
    And hence the code executes perfectly.

    Hope, I was clear.
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register