Help end child hunger

Statements and Functions

Prev: Data Types and Variables Next: Varying Variables

Control Flow Statements

The available options are pretty much the same as in C. There are conditional statements, like if-else, iteration statements like for, while and do-while.

	if (bool expression)
	for (initialization; bool expression; loop expression)
	while (bool expression)
	while (bool expression)

A few jumps are also defined:

  • continue – available in loops, causes a jump to the next iteration of the loop
  • break – available in loops, causes an exit of the loop
  • discard

The discard keyword can only be used in fragment shaders. It causes the termination of the shader for the current fragment without writing to the frame buffer, or depth.


As in C a shader is structured in functions. At least each type of shader must have a main function declared with the following syntax:

void main()

User defined functions may be defined. As in C a function may have a return value, and should use the return statement to pass out its result. A function can be void of course. The return type can have any type, but it can’t be an array.

The parameters of a function have the following qualifiers available:

  • in – for input parameters
  • out – for outputs of the function. The return statement is also an option for sending the result of a function.
  • inout – for parameters that are both input and output of a function

If no qualifier is specified, by default it is considered to be in.

A few final notes:

  • A function can be overloaded as long as the list of parameters is different.
  • Recursion behavior is undefined by specification.

An example of a function concludes this subsection.

vec4 toonify(in float intensity) {

	vec4 color;
	if (intensity > 0.98)
		color = vec4(0.8,0.8,0.8,1.0);
	else if (intensity > 0.5)
		color = vec4(0.4,0.4,0.8,1.0);
	else if (intensity > 0.25)
		color = vec4(0.2,0.2,0.4,1.0);
		color = vec4(0.1,0.1,0.1,1.0);		



Prev: Data Types and Variables Next: Varying Variables
© 2014 Suffusion theme by Sayontan Sinha