Ehsan
Ehsan

Reputation: 2285

string datatype in c

I am beginner in C, I am trying to write a function to return a string. I know that in C we don't have string data type. instead of these I try to use an array of chars but It's not my solution.

char[] my_function(int x){
    if(x>0)
        return 'greaterThanZero';
    else
        return 'smallerOrEqualOfZero';
}

please help me.

Upvotes: 0

Views: 10439

Answers (4)

anishsane
anishsane

Reputation: 20980

Use double quotes around greaterThanZero & smallerOrEqualOfZero.

Alternately, you can also return a single character (say g/s) & then use condition in the caller function.

NOTE: "greaterThanZero" will generally go onto the const section, not on stack. Hence it should be safe to return from function.

Upvotes: -1

Paul R
Paul R

Reputation: 213200

The return type needs to be const char * and the string literals need to be enclosed in double quotes:

const char * my_function(int x)
{
    if (x > 0)
        return "greaterThanZero";
    else
        return "lessThanOrEqualToZero";
}

int main(void)
{
    printf("my_function(1)  = %s\n", my_function(1));
    printf("my_function(0)  = %s\n", my_function(0));
    printf("my_function(-1) = %s\n", my_function(-1));
    return 0;
}

Note that single quotes are used for char variables:

char c = 'X';                // single character - single quotes
char *s = "Hello world!";    // string - double quotes

Upvotes: 6

banuj
banuj

Reputation: 3240

Use " instead of ' ('greaterThanZero' should be "greaterThanZero")

Upvotes: -1

MOHAMED
MOHAMED

Reputation: 43616

void my_function(int x, char **ret){
    if(x>0)
        *ret= "greaterThanZero";
    else
        *ret= "smallerOrEqualOfZero";
}

and in the main

int main() {
   char *string;
   my_function(1, &string);
   printf("%s",string);
}

Another way:

void my_function(int x, char *T){
        if(x>0)
            strcpy(T,"greaterThanZero");
        else
            strcpy(T, "smallerOrEqualOfZero");
    }

and in the main

int main() {
   char string[100];
   my_function(1, string);
   printf("%s",string);
}

Upvotes: 1

Related Questions