'Write a macro function to change the case of a string?

// I tried this code

 #include<iostream>
 using namespace std;

// Function to convert characters // of a string to opposite case

#define case_change(str)\
{\
    int ln = str.length();\

// Conversion according to ASCII values

 #define for (int i=0; i<ln; i++)\
            {\
                #ifdef (str[i]>='a' && str[i]<='z'){\
                    str[i] = str[i] - 32;\
                #endif}
                //Convert lowercase to uppercase

                #elifdef (str[i]>='A' && str[i]<='Z')\{\
                    str[i] = str[i] + 32;\
                #endif}\
                //Convert uppercase to lowercase


            #endif}
    }

// Driver function

int main()
{
    string str = "GeEkSfOrGeEkS";

    // Calling the Function
    case_change(str);

    cout << str;
    return 0;
}


Solution 1:[1]

You appear to have got if and ifdef confused. ifdef is used to test whether a macro has previously been defined, and enable functionality based on that definition. See this question: The role of #ifdef and #ifndef

Instead, you are trying to execute a particular piece of code based on a runtime test. For that, you want if instead.

As mentioned in comments, it generally considered bad practice to write a macro when you should be writing a function. Macro vs Function in C

Solution 2:[2]

#ifdef (str[i]>='a' && str[i]<='z')

should be

if (str[i]>='a' && str[i]<='z')

#ifdef doesn't make sense becausestr[i] must be evaluated at run time and the macro preprocessor only works at compile time.

Also #elifdef is not a legal token. For similar reason to above this should be else if.

Solution 3:[3]

You can use this code. I think it will help you

#include <iostream>
#include <bits/stdc++.h>
    
using namespace std;
    
#define CASE_CHANGE(str) ({        \
    int i = 0;                     \
    string op = "";                \
    while (str[i] != '\0') {       \
        if (isupper(str[i])) {     \
            op += tolower(str[i]); \
        }                          \
        else {                     \
            op += toupper(str[i]); \
        }                          \
        ++i;                       \
    }                              \
    op;                            \
    })

int main() {
    cout << CASE_CHANGE("babu");
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Korosia
Solution 2 john
Solution 3 llualpu