×

C Tutorial

C Basics

C Data Types

C Input/Output

C Operators

C Conditional Statements

C Control Statements

C Strings

C Functions

C Arrays

C Structure and Unions

C Pointers

C Preprocessor Directives

C Command-line Arguments

C File Handlings

C Graphics

C Advance Topics

C Tips and Tricks

C Important Topics

C Practice

Complex return statement using comma operator in c programming language.

In this tutorial we are going to learn about complex return statement in c programming using comma operator.

Here we will learn how we can use a return statement for other purpose with returning value to calling function?

Assign value to global variable and returning value to calling function

In the below code, a complex return statement is using for two purposes:

  • Assigning value to global variable.
  • Returning value to calling function.

Consider this program

#include <stdio.h>

//global variable
int status=0;

int testFunction(void){
	printf("Body of testFunction...\n");
	//complex return statement
	return (status=10, -3);
}

int main(){
	int return_value=0;
	
	printf("Main function started...\n");
	
	return_value=testFunction();
	printf("Value of status= %d\n",status);
	printf("Return value of testFunction is: %d\n",return_value);
	
	printf("End of main function...\n");
	
	return 0;
}

Output

Main function started...
Body of testFunction... 
Value of status= 10 
Return value of testFunction is: -3 
End of main function... 

Now consider the following complex return statement used in function

return (status=10, -3);

Here, 10 will be assigned to global variable status, that can be used further and -3 will be returned to the calling function main() that can also be used further.

When the statement (staus=10, -3) evaluates, first expression status =10 executes and assigns 10 to variable status and then second expression after comma -3 executes and according to operator precedence and associatively the final returnable value will be (-3).

For better understanding, consider the following statement, which may clear comma operator behaviour:

int x=(10,20);

When this statement executes value of x will be 20 because 10, 20 are in the brackets, so 10,20 will be evaluated first before assigning the value in variable x. Hence the final value inside the bracket will be (20).

Here is another statement:

int x=10,20;

In this statement there is no brackets and = has higher priority than comma (,) operator, so 10 will be assigned to x and the value of x will be 10.

Reference: https://en.wikipedia.org/wiki/Comma_operator




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.